-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_24.py
54 lines (49 loc) · 1.24 KB
/
prob_24.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
49
50
51
52
53
54
# 24. Swap Nodes in Pairs
# https://leetcode.com/problems/swap-nodes-in-pairs/
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
if not head.next:
return head
dummy = j = ListNode(-1)
dummy.next = head
while j and j.next and j.next.next:
l = j.next
r = l.next.next
l.next.next = l
j.next = l.next
l.next = r
j = l
return dummy.next
class Solution1(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
if not head.next:
return head
root = head.next
while head and head.next:
L = head
head = head.next
R = head.next
head.next = L
if R and R.next:
L.next = R.next
else:
L.next = R
head = R
return root