给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
链接经典题型
/**
* 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) {}
* };
*/
//方法1
class Solution
{
public:
ListNode* swapPairs(ListNode* head)
{
if(head == nullptr || head->next == nullptr)
{
return head;
}
ListNode *dummy = new ListNode(0);//ListNode dummy(0);
ListNode* pre = dummy;//作为头节点
pre->next = head;
while(pre->next != nullptr && pre->next->next != nullptr)
{
ListNode * cur = pre->next; //当前节点
ListNode * future = pre->next->next; //当前节点的下一个节点
//两两交换
pre->next = future;
cur->next = future->next;
future->next = cur;
//移动两个节点
pre = pre->next->next;
}
return dummy->next;
}
};
//方法2:递归
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;
}
};