Odd Even Linked List(LeetCode)

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.

You should try to do it in place. 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

Steps:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def oddEvenList(self, head):
 9         """
10         :type head: ListNode
11         :rtype: ListNode
12         """
13         if head is None:
14             return None
15         odd=head
16         even=head.next
17         evenHead=even
18         while even is not None and even.next is not None:
19             odd.next=even.next
20             odd=odd.next
21             even.next=odd.next
22             even=even.next
23         odd.next=evenHead
24         return head

 

posted @ 2016-04-05 16:45  随缘剑客  阅读(224)  评论(0)    收藏  举报