交换两两相连的链表节点

本文介绍了在LeetCode中处理链表问题,如何使用迭代和递归方法实现swapPairs函数,用于交换单链表中相邻节点的值。展示了两种不同的链表操作技巧。

. - 力扣(LeetCode)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
  typedef struct ListNode ListNode; 
  ListNode* newhead=(ListNode*)malloc(sizeof(ListNode));//创建伪节点
  newhead->next=head;//将该节点作为头节点
  ListNode* cur=newhead;//设置一个指针指向伪头节点,以便遍历链表
  while(cur->next!=NULL&&cur->next->next!=NULL)
  //不可以交换顺序,防止cur->next==NULL但是又执行cur->next->next!=NULL的操作,导致出现空指针->next的操作
  {
     ListNode* temp1=cur->next;//如:保存1节点
     ListNode* temp2=cur->next->next->next;//如:保存3节点
     cur->next=cur->next->next;//让伪头节点指向真正的第二个节点 如:2
     cur->next->next=temp1;//2->1
     temp1->next=temp2;// 1->3
     cur=cur->next->next;//移动cur
  }
  return newhead->next;//返回真正的头节点
}

利用递归也可以。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
  typedef struct ListNode ListNode; 
  //顺序是先记录2(*newhead=head->next),
  //再连接2->3(newhead->next),
  //再连1->4(head->next=swapPairs(newhead->next))
  //再连2->1(newhead->next=head;).
  if(!head||!head->next) return head;//如果只有一个或者0个节点,就直接返回头指针
  ListNode *newhead=head->next;//新的头节点是原头节点的next,也就是2
  head->next=swapPairs(newhead->next);//原头节点的下一个节点是swapPairs(newhead->next)
  //而swapPairs(newhead->next)中的参数此时是3,而函数操作是取3后面一个节点
  newhead->next=head;//新头节点的下一个应该是原头节点
  return newhead;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值