-
Notifications
You must be signed in to change notification settings - Fork 0
/
24. Swap Nodes in Pairs.py
46 lines (41 loc) · 1.14 KB
/
24. Swap Nodes in Pairs.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs_loop(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next and cur.next.next:
first = cur.next
second = cur.next.next
cur.next = second
first.next = second.next
second.next = first
cur = cur.next.next
return dummy.next
def swapPairs(self, head):
#recurse
if not head or not head.next: return head
new_start = head.next.next
head, head.next = head.next, head
head.next.next = self.swapPairs(new_start)
return head
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
s = Solution()
s.swapPairs(node1)