本文最后更新于633 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
题目链接/文章讲解/视频讲解: https://programmercarl.com/0024.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.html
1.其实刚看这个题我没什么特别好的思路,我以为2和1交换完了1和3交换呢,反正思路还是挺乱的,想到说用这个虚拟头结点,然后进行遍历,但是想不好确定什么时候终止循环,这个条件我要确定好久。
2.看了代码随想录之后,明确了这个交换的次序,以及循环终止条件。这个问题就还挺简单。
CPP
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *cur = dummyHead;
ListNode *temp = new ListNode(0);
ListNode *temp1 = new ListNode(0);
while(cur->next !=NULL && cur->next->next != NULL){
temp = cur->next;
temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp->next = temp1;
cur = cur->next->next;
}
return dummyHead->next;
}
};