给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
.
-----------------------------------------------------------------------------------------------------------
思路:
指针运算
-1 1 2 3 4
one two three
1、新建一个节点-1,做头结点。使two=one->next和three = one->next->next(这有个小技巧,把前面那两个等式写在while循环里面,这样最后就移动一个one指针就可以了,其余两个直接跟着动,而不用移动三个指针)
2、找出one和two和three的next之间关系,重排指针(从后往前three-two-one)
twoPtr->next = threePtr->next;
threePtr->next = twoPtr;
onePtr->next = threePtr;
3、 将one指针后移两步,onePtr = twoPtr;
/**
* 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) {
if (!head)return nullptr;
ListNode* newNode = new ListNode(-1);
newNode->next = head;
ListNode* onePtr = newNode;
while (onePtr->next && onePtr->next->next)
{
ListNode* twoPtr = onePtr->next;
ListNode* threePtr = onePtr->next->next;
twoPtr->next = threePtr->next;
threePtr->next = twoPtr;
onePtr->next = threePtr;
onePtr = twoPtr;
}
return newNode->next;
}
};
另一个代码是0ms,空间复杂度比较小,还是用全局变量速度快
/**
* 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) {
if (!head)return nullptr;
ListNode* newNode = new ListNode(-1);
newNode->next = head;
ListNode* onePtr = newNode;
while (onePtr->next && onePtr->next->next)
{
ListNode* twoPtr = onePtr->next;
ListNode* threePtr = onePtr->next->next;
twoPtr->next = threePtr->next;
threePtr->next = threePtr;
onePtr->next = threePtr;
onePtr->next->next = twoPtr;
onePtr = onePtr->next->next;
}
return newNode->next;
}
};