File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Time: O(n)
2+ # Space: O(1)
3+
4+ # Given a singly linked list, group all odd nodes
5+ # together followed by the even nodes.
6+ # Please note here we are talking about the node number
7+ # and not the value in the nodes.
8+ #
9+ # You should try to do it in place. The program should run
10+ # in O(1) space complexity and O(nodes) time complexity.
11+ #
12+ # Example:
13+ # Given 1->2->3->4->5->NULL,
14+ # return 1->3->5->2->4->NULL.
15+ #
16+ # Note:
17+ # The relative order inside both the even and odd groups
18+ # should remain as it was in the input.
19+ # The first node is considered odd, the second node even
20+ # and so on ...
21+
22+ # Definition for singly-linked list.
23+ # class ListNode(object):
24+ # def __init__(self, x):
25+ # self.val = x
26+ # self.next = None
27+
28+ class Solution (object ):
29+ def oddEvenList (self , head ):
30+ """
31+ :type head: ListNode
32+ :rtype: ListNode
33+ """
34+ if head :
35+ odd_tail , cur = head , head .next
36+ while cur and cur .next :
37+ even_head = odd_tail .next
38+ odd_tail .next = cur .next
39+ odd_tail = odd_tail .next
40+ cur .next = odd_tail .next
41+ odd_tail .next = even_head
42+ cur = cur .next
43+ return head
You can’t perform that action at this time.
0 commit comments