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.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
解:給一個(gè)列表,所在列表位置為奇數(shù)為的節(jié)點(diǎn)放前面,偶數(shù)位的放后面。注意,奇偶之間要保持原來的順序。而且,不是值的奇偶,是位置即序號(hào)的奇偶。
思路:需要一個(gè)指針遍歷原列表curr,她的步長為2,一直指向偶數(shù)位,在跳躍之前把下一個(gè)節(jié)點(diǎn)給奇數(shù)位。

class Solution(object):
def oddEvenList(self, head):
# :type head: ListNode
# :rtype: ListNode
if not head or not head.next:
return head
odd = head
even = head.nextw
curr = even
while curr and curr.next:
odd.next = curr.next
odd = odd.next
curr.next = curr.next.next
curr = curr.next
odd.next = even
return head