两两交换链表中的节点|递归
两两交换链表中的节点
链表中每两两相邻的节点将其对调位置,涉及的主要操作位交换节。但需要注意初始位置的交换即返回值,以及奇数个节点的处理方法,这里给出两种方法,迭代和递归。其中递归又分为两种。
对应题目24. 两两交换链表中的节点💫
迭代法
同样的使用虚拟头节点进行操作,两个好处。一是可以方便最后的返回值即为头节点的next
。二是方便交换起始两个节点。实现方式具体看代码。分析复杂度,对于时间复杂度需要遍历所有节点所以为\(O(N)\);空间复杂度为\(O(1)\)。
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* cur = dummy;
while(cur->next != nullptr &&
cur->next->next != nullptr) {
//difine two temporary pointers to store the nodes after 'cur'.
ListNode* p = cur->next;
ListNode* q = cur->next->next->next;
//exchange those pointers.
cur->next = cur->next->next;
cur->next->next = p;
cur->next->next->next = q;
cur = cur->next->next;
}
return dummy->next;
}
递归
对于递归,这里有两种方法。一是由上面的迭代方法改过的,二是不带虚拟头节点的写法,但是总体思路不变。分析复杂度,时间复杂度一样为\(O(N)\);空间复杂度取决于调用的栈空间所以也是\(O(N)\)。
// dummyHead
ListNode* swap(ListNode* cur) {
if(cur->next == nullptr || cur->next->next == nullptr) {
return cur->next;
}
ListNode* p = cur->next;
ListNode* q = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = p;
cur->next->next->next = q;
swap(cur->next->next);
return cur->next;
}
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode();
dummy->next = head;
return swap(dummy);
}
// no dummyHead
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode* p = head->next;
head->next = swapPairs(p->next);
p->next = head;
return p;
}