题目描述:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
学习记录:
想法就是依次记录三个指针a,b,c表示上一个节点、交换节点1,交换节点2;通过指针的操作交换位置,然后依次往后进行。这里想完后看了一下题解,应该是没问题的,可以实现,就去写了,代码如下,一遍过!
需要注意的问题
1.第一次交换情况和别的不同,因为没有前驱,但可以在头部再插入一个指针,就可以避免第一个指针没有前驱的情况了,能够将问题一般化,要学会使用。
2.head在交换后是改变位置了的,需要head=save->next,找到新的头。
3.new---delete
/**
* 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) {
if(head==nullptr || head->next==nullptr) return head;
ListNode* save=new ListNode;
save->next=head;
ListNode* a=save;
ListNode* b=a->next;
ListNode* c=b->next;
while(a->next!=nullptr && a->next->next!=nullptr)
{
b=a->next;c=b->next;
a->next=c;
b->next=c->next;
c->next=b;
a=b;
}
head=save->next;
delete save;
return head;
}
};
题解:
第二种迭代和我们思路一样,学一下第一种递归方法。
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;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/swap-nodes-in-pairs/solution/liang-liang-jiao-huan-lian-biao-zhong-de-jie-di-91/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。