力扣-链表-24 两两交换链表中的节点
思路1
设置虚拟节点作为pre,第一个节点是cur,后一个是post,不断更换顺序并且更改好pre的next
代码1
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head) return head;
ListNode* cur = head;
ListNode* post = head->next;
ListNode* dummpy_head = new ListNode();
dummpy_head->next = head;
ListNode* pre = dummpy_head;
while(post){
ListNode* tmpCur = new ListNode();
ListNode* tmpPost = new ListNode();
if(post->next && post->next->next){
tmpCur = post->next;
tmpPost = tmpCur->next;
}else{
tmpCur = nullptr;
tmpPost = nullptr;
}
pre->next = post;
cur->next = post->next;
post->next = cur;
pre = cur;
cur = tmpCur;
post = tmpPost;
}
return dummpy_head->next;
}
};