-
Notifications
You must be signed in to change notification settings - Fork 1
/
24. Swap Nodes in Pairs.py
45 lines (37 loc) · 1.06 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
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_to_ListNode(self, l: list):
if len(l) == 0:
return None
else:
return ListNode(l[0],self.list_to_ListNode(l[1::]))
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
pointer = head
while pointer != None:
if pointer.next == None:
break
else:
temp = pointer.val
pointer.val = pointer.next.val
pointer.next.val = temp
pointer = pointer.next.next
return head
sol = Solution()
l = []
head = ListNode().list_to_ListNode(l)
new_head = sol.swapPairs(head)
print(new_head)
"""
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
second = head.next
head.next = self.swapPairs(second.next)
second.next = head
return second
"""