资讯专栏INFORMATION COLUMN

328. Odd Even Linked List

abson / 577人阅读

</>复制代码

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

</>复制代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def oddEvenList(self, head: ListNode) -> ListNode:
  8. # If zero, one or two elements, then solved
  9. if head == None or head.next == None or head.next.next == None:
  10. return head
  11. # Two pointers
  12. p = head
  13. n = head.next
  14. t = None
  15. while n.next:
  16. # If there is even element
  17. if n.next.next:
  18. # Keep it for now for both n and p
  19. t = n.next.next
  20. m = p.next
  21. p.next = n.next
  22. p = p.next
  23. # Recover link for p and n
  24. p.next = m
  25. n.next = t
  26. n = n.next
  27. else:
  28. # Save and insert odd
  29. t = p.next
  30. p.next = n.next
  31. p = p.next
  32. p.next = t
  33. n.next = None
  34. 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元查看
<