File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def swapPairs (self , head ):
3
+ pre_head = ListNode (- 1 )
4
+ curr = head
5
+ prev = pre_head
6
+
7
+ if not curr or not curr .next : return head
8
+
9
+ while curr and curr .next :
10
+ temp_next = curr .next .next
11
+
12
+ prev .next = curr .next
13
+ curr .next .next = curr
14
+ curr .next = temp_next
15
+
16
+ prev = curr
17
+ curr = temp_next
18
+
19
+ return pre_head .next
20
+
21
+
22
+ from collections import deque
23
+ class Solution (object ):
24
+ def swapPairs (self , head ):
25
+ curr = head
26
+ q1 = deque ([])
27
+ q2 = deque ([])
28
+ seq = 0
29
+ while curr :
30
+ if seq % 2 == 0 :
31
+ q2 .append (curr )
32
+ else :
33
+ q1 .append (curr )
34
+
35
+ temp = curr .next
36
+ curr .next = None #clear old link
37
+ curr = temp
38
+ seq += 1
39
+
40
+ if seq == 1 :
41
+ return head
42
+
43
+ use_q1 = True
44
+ pre_head = ListNode (- 1 )
45
+ curr = pre_head
46
+ while q1 or q2 :
47
+ if use_q1 :
48
+ if not q1 : break
49
+ curr .next = q1 .popleft ()
50
+ else :
51
+ curr .next = q2 .popleft ()
52
+ curr = curr .next
53
+ use_q1 = not use_q1
54
+
55
+ if q2 : curr .next = q2 .popleft () #odd length of linked list
56
+
57
+ return pre_head .next
You can’t perform that action at this time.
0 commit comments