题目描述

思路
在链表最前面设置一个pre指针,利用pre, cur, post三个指针即可完成,上述的任务,不难,分析好链表关系即可
题解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* pre=dummy;
while(pre->next&&pre->next->next){
ListNode* cur=pre->next;
ListNode* post=pre->next->next;
pre->next=post;
cur->next=post->next;
post->next=cur;
pre=pre->next->next;
}
return dummy->next;
}
};

还可以优化,尝试回溯等方法
本文介绍了一种在链表中交换每对相邻节点的算法,通过使用预节点简化了操作,确保了链表的正确性。该算法适用于任何包含至少两个节点的链表,且不需要额外的空间。
676

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



