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.
# 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
"""

本文介绍了一种在不额外使用空间的情况下对链表进行奇偶节点分组的方法,确保奇数节点位于前部,偶数节点随后,并保持原有的相对顺序。
494

被折叠的 条评论
为什么被折叠?



