zoukankan      html  css  js  c++  java
  • leetcode 奇偶链表 python

    要求空间复杂度O(1) 那就只能用指针不断改链表的指针, 不能建立新的内存

    时间复杂度O(1) 一遍遍历 不能嵌套循环

    我的思想是:

      1 如果链表元素数量小于等于2个,那就无法操作

      2 能操作的情况下:

        cur指向第一个元素    不断后移 标记奇数下标的元素

        odd 指向第二个元素   不断后移标记偶数下标的元素

        tail指向尾巴元素  时刻保持指向队尾

        mid指向尾巴元素   标记最开始的时候的队尾元素

        循环:

          把cur.next 改成odd.next , odd.next改为null  这样 第一个偶数下标元素移除了链表

          把 tail.next 改成odd  tail后移到tail.next上    这样,第一个偶数元素放到了队尾 并将队尾指针后移

          cur后移一位 指向之前第三个元素 也就是整个链表第二个下标为奇数的元素

          ----------第一轮结束  继续若干轮

        什么时候移动完了:

          1 如果链表是奇数个元素:

            cur一直指向原本奇数下标的元素并不断后移,如果cur和mid(原本的队尾)  碰头了 说明 链表改完了

          2 如果链表是偶数个元素:

            mid是原本是原本的队尾元素,但是他是第偶数个,某一轮循环结束发现 mid.next是null

              说明他被移动到了队尾,也就改完整个链表了

    代码:

     1 # Definition for singly-linked list.
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     def oddEvenList(self, head):
     9         """
    10         :type head: ListNode
    11         :rtype: ListNode
    12         """
    13         tail = head
    14         cur = head
    15         while tail.next is not None:
    16             tail = tail.next
    17         mid = tail
    18         while cur.val != mid.val or mid.next is not None:
    19             odd = cur.next
    20             cur.next = odd.next
    21             odd.next = None
    22             cur = cur.next
    23             tail.next = odd
    24             tail = tail.next
    25         return head
  • 相关阅读:
    基础最短路(模板 bellman_ford)
    UVA-12304 Race(递推)
    How do you add?(递推)
    Coconuts, Revisited(递推+枚举+模拟)
    UVA-10726 Coco Monkey(递推)
    UVA-10995 Educational Journey
    UVA-10339 Watching Watches
    【React】377- 实现 React 中的状态自动保存
    【JS】376- Axios 使用指南
    【Nodejs】375- 如何加快 Node.js 应用的启动速度
  • 原文地址:https://www.cnblogs.com/Lin-Yi/p/9608354.html
Copyright © 2011-2022 走看看