zoukankan      html  css  js  c++  java
  • LeetCode-328. Odd Even Linked List

    328. Odd Even Linked List

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

    Solution

    使用两个指针。

    # 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):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head or not head.next:
                return head
            odd = head
            even = head.next
            evenHead = even
            while even and even.next:
                odd.next = odd.next.next
                even.next = even.next.next
                odd = odd.next
                even = even.next
            odd.next = evenHead
            return head
    
  • 相关阅读:
    gulp编译sass
    Material Design学习
    js爬虫心得
    js爬虫
    angularjs
    sass心得
    矩阵与线性代数学习笔记
    2-SAT学习笔记
    一个有趣的题目【二分答案,2-SAT,线段树优化】
    vijos训练之——星辰大海中闪烁的趣题
  • 原文地址:https://www.cnblogs.com/binwone/p/6245624.html
Copyright © 2011-2022 走看看