328-Odd Even Linked List leecode

作者: 老豆腐 | 来源:发表于2018-04-23 21:36 被阅读22次

    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.

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

    思路:需要一个指针遍历原列表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
    

    相关文章

      网友评论

        本文标题:328-Odd Even Linked List leecode

        本文链接:https://www.haomeiwen.com/subject/jokrlftx.html