-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy path24swapnodesinpairs.py
48 lines (40 loc) · 1.02 KB
/
24swapnodesinpairs.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
47
48
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return head
temp = []
while head is not None:
temp.append(head.val)
head = head.next
i = 0
while i + 1 < len(temp):
t = temp[i]
temp[i] = temp[i + 1]
temp[i + 1] = t
i = i + 2
h = ListNode(temp[0])
c = ListNode(temp[1])
h.next = c
for j in range(2,len(temp)):
node = ListNode(temp[j])
c.next = node
c = c.next
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
s = Solution()
new_head = s.swapPairs(head)
while new_head is not None:
print(new_head.val)
new_head = new_head.next