两两交换链表中的节点
一开始自己的思路只是两两交换,并没有说涉及到前一个节点。实际上两两交换涉及到了三个节点
使用虚拟头结点,这样一次性处理三个节点。且每次组里第一个节点其实数值没变。
class Solution {
public:ListNode* swapPairs(ListNode* head) {ListNode* dummyhead = new ListNode(0);dummyhead->next=head;ListNode* cur=dummyhead;while(cur->next != nullptr && cur->next->next != nullptr){ListNode* temp1 = cur->next;ListNode* temp2 = cur->next->next->next;cur->next=cur->next->next;cur->next->next=temp1;temp1->next=temp2;cur=cur->next->next;}return dummyhead->next;}
};
迭代法:发现的规律是,本质上一组同时改变新的节点。重复的是,原来head-》next也就是newhead变成了新的头结点。而且要每次返回交换顺序的头结点给上一组。
class Solution {
public:ListNode* swapPairs(ListNode* head) {if(head == nullptr || head->next == nullptr) return head;ListNode* newhead= head->next;head->next = swapPairs(newhead->next);newhead->next=head;return newhead;}
};