Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/description/
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Thoughts
因为head也要翻转,用dummy作为新head
每次把node后面两个翻转,因此牵扯到它后面三个node, 当它后面只有一个时不用翻转,自动退出。
Code
/**
* 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_node(-1);
auto dummy = &dummy_node, node = dummy;
dummy->next = head;
while (node->next != NULL && node->next->next != NULL) {
auto n1 = node->next, n2 = n1->next, n3 = n2->next;
node->next = n2;
n2->next = n1;
n1->next = n3;
node = n1;
}
return dummy->next;
}
};
Analysis
做题耗时16min
Errors:
node.next.next = tmp
条件是后两个都不为空。
时间复杂度O(n)
Last updated
Was this helpful?