链表之两两交换链表中的相邻节点

问题

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

在这里插入图片描述

在这里插入图片描述

解决

思路如下

在这里插入图片描述

public static Node changeAdjoiningNode(Node<Integer> headNode){

        Node<Integer> virtualNode = new Node(-1,null);
        // 虚拟节点下一节点 指向头节点
        virtualNode.setNext(headNode);
        // current指向虚拟节点
        Node currentNode = virtualNode;

        // 实际交换元素1,2 存在
        while (currentNode.getNext() != null && currentNode.getNext().getNext()!= null){

            System.out.println();
            // 缓存节点3
            Node temp = headNode.getNext().getNext();
            // currentNode下一节点指向 节点2
            currentNode.setNext(headNode.getNext());
            // 节点2 下一节点 指向 节点1
            headNode.getNext().setNext(headNode);
            // 节点1  下一节点 指向  节点3
            headNode.setNext(temp);
            // 下移一位
            currentNode = headNode;
            headNode = headNode.getNext();
        }

        return virtualNode.getNext();

    }
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一种实现方式: ```c #include <stdio.h> #include <stdlib.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* swapPairs(struct ListNode* head) { struct ListNode *prev = NULL, *curr = head, *next = NULL; while (curr != NULL && curr->next != NULL) { next = curr->next; curr->next = next->next; next->next = curr; if (prev == NULL) { head = next; } else { prev->next = next; } prev = curr; curr = curr->next; } return head; } int main() { struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->val = 1; head->next = (struct ListNode*)malloc(sizeof(struct ListNode)); head->next->val = 2; head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode)); head->next->next->val = 3; head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode)); head->next->next->next->val = 4; head->next->next->next->next = NULL; printf("Before swapping: "); struct ListNode *curr = head; while (curr != NULL) { printf("%d ", curr->val); curr = curr->next; } printf("\n"); head = swapPairs(head); printf("After swapping: "); curr = head; while (curr != NULL) { printf("%d ", curr->val); curr = curr->next; } printf("\n"); return 0; } ``` 这个程序使用了三个指针 `prev`,`curr` 和 `next` 来交换相邻两个节点。在每个循环迭代,我们先保存当前节点的下一个节点 `next`,然后将当前节点的 `next` 指向 `next` 的下一个节点,再将 `next` 的 `next` 指向当前节点。最后,我们需要将前一个节点 `prev` 的 `next` 指向 `next`,这样交换后的链表就连起来了。注意,还需要特别处理一下头指针。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白鸽呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值