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
Analysis
做题耗时16min
Errors:
node.next.next = tmp
条件是后两个都不为空。
时间复杂度O(n)
Last updated
Was this helpful?