两两交换链表中的节点(代码步骤+图解)

思路

  • 这里采用虚拟头结点,方便获取实际头结点
  • 这里需要注意每一次调转指针后,是否还能获取需要用到的实际结点,可以采用临时指针保存需要获取使用的结点。
  • 指针调转的顺序并不是固定的,只要能够获取正确的结点就行。

图解

代码看不懂就和图一起看,黄色代码行下就是对应链表变化。

题目

解题示例代码

function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
var swapPairs = function (head) {
  // 创建一个虚拟头节点,方便操作
  let ret = new ListNode(0, head), temp = ret;
  // 注意遍历终止条件:当temp后面还有两个节点时,进行交换
  while (temp.next && temp.next.next) {
    // 保存这两个节点,方便后续获取
    let cur = temp.next.next, pre = temp.next;
    // 将pre节点指向cur的下一个节点
    pre.next = cur.next;
    // 将cur节点指向pre
    cur.next = pre;
    // 将temp节点指向cur,完成交换
    temp.next = cur;
    // 更新temp为pre,继续下一轮交换
    temp = pre;
  }
  // 返回虚拟头节点的下一个节点,即交换后的链表头节点
  return ret.next;
};

指针调转顺序不是固定的,也可以用以下调换:

    while (temp.next && temp.next.next) {
        let pre = temp.next
        let cur = temp.next.next
        temp.next = cur
        pre.next = cur.next
        cur.next = pre
        temp = pre
    }
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是交换链表节点的C语言代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node* next; } Node; // 定义交换链表节点的函数 void swapNodes(Node** head, int x, int y) { // 如果x和y相同,直接返回 if (x == y) { return; } // 定义需要交换节点和它们的前驱节点 Node *prevX = NULL, *currX = *head; Node *prevY = NULL, *currY = *head; // 寻找需要交换节点和它们的前驱节点 while (currX != NULL && currX->data != x) { prevX = currX; currX = currX->next; } while (currY != NULL && currY->data != y) { prevY = currY; currY = currY->next; } // 如果x或y不存在于链表,直接返回 if (currX == NULL || currY == NULL) { return; } // 如果x不是头节点,更新前驱节点的next指针 if (prevX != NULL) { prevX->next = currY; } else { // 如果x是头节点,更新头指针 *head = currY; } // 如果y不是头节点,更新前驱节点的next指针 if (prevY != NULL) { prevY->next = currX; } else { // 如果y是头节点,更新头指针 *head = currX; } // 交换节点的next指针 Node* temp = currY->next; currY->next = currX->next; currX->next = temp; } // 定义输出链表的函数 void printList(Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } int main() { // 创建一个测试用例链表 Node* head = (Node*)malloc(sizeof(Node)); head->data = 1; head->next = (Node*)malloc(sizeof(Node)); head->next->data = 2; head->next->next = (Node*)malloc(sizeof(Node)); head->next->next->data = 3; head->next->next->next = (Node*)malloc(sizeof(Node)); head->next->next->next->data = 4; head->next->next->next->next = NULL; // 输出原始链表 printf("原始链表: "); printList(head); printf("\n"); // 交换节点 swapNodes(&head, 2, 4); // 输出交换后的链表 printf("交换后的链表: "); printList(head); printf("\n"); return 0; } ``` 以上代码将创建一个测试用例链表,输出原始链表交换节点,输出交换后的链表。可以根据自己的需要修改测试用例链表
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值