Leetcode #328. Odd Even Linked List

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.

The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

 1 class Solution(object):
 2     def oddEvenList(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: ListNode
 6         """
 7         if head == None or head.next == None:
 8             return head
 9             
10         dummy = odd = head
11         connectNode = even = head.next
12         
13 
14         while even and odd:
15             t = even.next
16             if t == None:
17                 break
18             
19             odd.next = odd.next.next
20             # or odd.next = even.next
21             odd = odd.next
22             
23             even.next = even.next.next
24             # or even.next = odd.next
25             even = even.next
26         
27         odd.next = connectNode
28         
29         return dummy
30         

 

posted @ 2016-11-27 10:05  lettuan  阅读(116)  评论(0编辑  收藏  举报