leetcode328 Odd Even Linked List

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 """

 

以上是关于leetcode328 Odd Even Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-328. Odd Even Linked List

Leetcode 328. Odd Even Linked List

LeetCode OJ 328Odd Even Linked List

LeetCode OJ 328Odd Even Linked List

leetcode328 Odd Even Linked List

<LeetCode OJ> 328. Odd Even Linked List