LeetCode 24两两交换链表中的节点Easy
-
题目简述:给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
-
输入:1->2->3->4 输出:2->1->4->3
-
思路:迭代
画图理解 p -> a -> b -> c
创建虚拟头节点dummy,交换a、b节点的过程,首先将p的下一个指向b,其次a的下一个指向b的下一个,然后b的下一个指向a,最后将p的位置向前移动一个位置,不断更新整个链表,直到遇到空节点结束。
/**
* 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;
auto p = dummy;
while(p->next != nullptr && p->next->next != nullptr)
{
auto a = p->next;
auto b = a->next;
p->next = b;
a->next = b->next;
b->next = a;
p = a;
}
return dummy->next;
}
};
- 思路二:递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* first) {
if (first == nullptr || first->next == nullptr) return first;
auto second = first->next;
first->next = swapPairs(second->next);
second->next = first;
return second;
}
};