-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOdd even linked list.py
64 lines (46 loc) · 1.2 KB
/
Odd even linked list.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
55
56
57
58
59
60
61
62
63
64
# Definition for singly-linked list.
def stringToListNode(nums):
# Generate list from the input
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in nums:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def listNodeToString(node):
if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def oddEvenList(head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next or not head.next.next:
return head
odd, even = head, head.next
first_even = head.next
while True:
next_odd = even.next
odd.next = next_odd
even.next = next_odd.next
next_odd.next = first_even
odd = next_odd
even = even.next
if not even or not even.next:
break
return head
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
head = stringToListNode(nums)
ans = oddEvenList(head)
print(listNodeToString(ans))