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

被折叠的 条评论
为什么被折叠?



