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 @aadarshjajodia for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
两个起点,分别记录,最后整合。
需要注意的是,见代码中注释,防止形成环。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
if not head:
return
odd = ListNode(-1)
eve = ListNode(-1)
t_odd = odd
t_eve = eve
i = 0
while head:
i += 1
if i % 2 == 0:
odd.next = head
odd = odd.next
else:
eve.next = head
eve = eve.next
head = head.next
#print 'end',t_odd.next.val
eve.next = t_odd.next
#这句非常重要,没加的话,就形成了环,比如123,则3的后面还是2,然后就变成12323232323232……
odd.next = None
return t_eve.next
"""
:type head: ListNode
:rtype: ListNode
"""