码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode328 Odd Even Linked List

时间:2020-02-01 23:19:31      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:follow   previous   together   while   div   null   example   input   class   

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

 

leetcode328 Odd Even Linked List

标签:follow   previous   together   while   div   null   example   input   class   

原文地址:https://www.cnblogs.com/yawenw/p/12250401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!