资讯专栏INFORMATION COLUMN

328. Odd Even Linked List

abson / 382人阅读

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.

https://leetcode.com/problems...

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        # If zero, one or two elements, then solved
        if head == None or head.next == None or head.next.next == None:
            return head

        # Two pointers
        p = head
        n = head.next
        t = None

        while n.next:
            # If there is even element
            if n.next.next:
                # Keep it for now for both n and p
                t = n.next.next
                m = p.next
                p.next = n.next
                p = p.next
                # Recover link for p and n
                p.next = m
                n.next = t
                n = n.next
            else:
                # Save and insert odd
                t = p.next
                p.next = n.next
                p = p.next
                p.next = t
                n.next = None

        return head
                

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43625.html

相关文章

  • leetcode 328. Odd Even Linked List

    摘要:最后将奇数链表尾连到偶数链表头即可。改进的思路在于减少额外的变量创建。奇数指针的初始值为,而偶数指针的初始值为。则下一个奇数值位于上,此时将该奇数指针移动到上之后,偶数指针的值则为。 题目要求 Given a singly linked list, group all odd nodes together followed by the even nodes. Please note...

    Vultr 评论0 收藏0
  • [LeetCode] 328. Odd Even Linked List

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

    Invoker 评论0 收藏0
  • LeetCode 328:奇偶链表 Odd Even Linked List

    摘要:给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。需要记录偶数位节点的第一个节点,因为这是偶数链表的头节点,最后拼接链表时要用奇数链表的尾节点连接该节点。 ​给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成...

    yeooo 评论0 收藏0
  • LeetCode 328:奇偶链表 Odd Even Linked List

    摘要:给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。需要记录偶数位节点的第一个节点,因为这是偶数链表的头节点,最后拼接链表时要用奇数链表的尾节点连接该节点。 ​给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成...

    flybywind 评论0 收藏0
  • [LeetCode/LintCode] Odd Even Linked List

    Problem 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. Example Example:Given...

    awokezhou 评论0 收藏0

发表评论

0条评论

abson

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<