LeetCode #24 Swap Nodes in Pairs

Problem

Given a linked list, swap every two adjacent nodes and return its head.

Example

1
Given 1->2->3->4, you should return the list as 2->1->4->3.

Note

Can solve this problem by using only constant extra space.

Solution

Method: Iterative

Time Complexity: O(n)

Space Complexity: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head

dummy = ListNode(None)
dummy.next = head
pre = dummy
left = head
right = head.next

while left and right:
left.next = right.next
pre.next = right
right.next = left
pre = pre.next.next
left = pre.next
if left:
right = left.next
else:
right = None

return dummy.next

Reference

7-8 lines C++ / Python / Ruby