Skip to content

Commit 6d74834

Browse files
authored
Create Odd Even Linked List.py
1 parent f14e8b9 commit 6d74834

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Odd Even Linked List.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
'''
2+
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
3+
4+
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
5+
6+
Example 1:
7+
8+
Input: 1->2->3->4->5->NULL
9+
Output: 1->3->5->2->4->NULL
10+
Example 2:
11+
12+
Input: 2->1->3->5->6->4->7->NULL
13+
Output: 2->3->6->7->1->5->4->NULL
14+
Note:
15+
16+
The relative order inside both the even and odd groups should remain as it was in the input.
17+
The first node is considered odd, the second node even and so on ...
18+
'''
19+
20+
# Definition for singly-linked list.
21+
# class ListNode(object):
22+
# def __init__(self, x):
23+
# self.val = x
24+
# self.next = None
25+
26+
class Solution(object):
27+
def oddEvenList(self, head):
28+
"""
29+
:type head: ListNode
30+
:rtype: ListNode
31+
"""
32+
odd_dummy = ListNode(0)
33+
odd_cur = odd_dummy
34+
even_dummy = ListNode(0)
35+
even_cur = even_dummy
36+
37+
cur = head
38+
count = 0
39+
while cur:
40+
count += 1
41+
if count & 1:
42+
odd_cur.next = cur
43+
odd_cur = odd_cur.next
44+
else:
45+
even_cur.next = cur
46+
even_cur = even_cur.next
47+
cur = cur.next
48+
49+
odd_cur.next = even_dummy.next
50+
even_cur.next = None
51+
52+
return odd_dummy.next
53+
54+

0 commit comments

Comments
 (0)