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.
解:給一個列表荆残,所在列表位置為奇數(shù)為的節(jié)點放前面炬搭,偶數(shù)位的放后面慈鸠。注意墓猎,奇偶之間要保持原來的順序得封。而且酌住,不是值的奇偶泪掀,是位置即序號的奇偶趁曼。
思路:需要一個指針遍歷原列表curr,她的步長為2坯门,一直指向偶數(shù)位微饥,在跳躍之前把下一個節(jié)點給奇數(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