您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页正文

328-Odd Even Linked List leecode

来源:二三娱乐

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

解:给一个列表,所在列表位置为奇数为的节点放前面,偶数位的放后面。注意,奇偶之间要保持原来的顺序。而且,不是值的奇偶,是位置即序号的奇偶。

思路:需要一个指针遍历原列表curr,她的步长为2,一直指向偶数位,在跳跃之前把下一个节点给奇数位。


图解.jpg
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
Top