zoukankan      html  css  js  c++  java
  • leetcode328 Odd Even Linked List

     1 """
     2 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.
     3 
     4 You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
     5 
     6 Example 1:
     7 
     8 Input: 1->2->3->4->5->NULL
     9 Output: 1->3->5->2->4->NULL
    10 
    11 Example 2:
    12 
    13 Input: 2->1->3->5->6->4->7->NULL
    14 Output: 2->3->6->7->1->5->4->NULL
    15 
    16 """
    17 
    18 class ListNode:
    19     def __init__(self, x):
    20         self.val = x
    21         self.next = None
    22 class Solution(object):
    23     def oddEvenList(self, head):
    24         if head == None or head.next == None:  #头结点限定条件
    25             return head
    26 
    27         odd = head
    28         even = head.next
    29         t = even   #!!!记录偶数结点的起始位置
    30         while even != None and even.next != None:
    31             #!!!遍历结点,保持奇数偶数结点的相对位置
    32             odd.next = even.next  #连接奇数结点
    33             odd = odd.next        #调整位置
    34             even.next = odd.next  #连接偶数结点
    35             even = even.next      #调整位置
    36         odd.next = t              #整合链表
    37         return head
    38 
    39 """
    40 注意题意,
    41 这里的奇数节点和偶数节点指的是节点编号的奇偶性,
    42 而不是节点的值的奇偶性。
    43 此类题只需要遍历一遍链表,需要两个指针来进行操作
    44 如previous,current(leetcode83)
    45 传送门https://blog.csdn.net/qq_17550379/article/details/80654239
    46 """
  • 相关阅读:
    Linux关闭防火墙和selinux
    Linux内存VSS,RSS,PSS,USS解析
    JS 将有父子关系的数组转换成树形结构数据
    npm install报错类似于npm WARN tar ENOENT: no such file or directory, open '*** ode_modules.staging***
    react-native之文件上传下载
    Markdown语法简记
    MySQL运维开发
    股票投资
    数据仓库原理与实战
    python基础
  • 原文地址:https://www.cnblogs.com/yawenw/p/12250401.html
Copyright © 2011-2022 走看看