题目描述
思路
在链表最前面设置一个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;
}
};
还可以优化,尝试回溯等方法