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...
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
# If zero, one or two elements, then solved
if head == None or head.next == None or head.next.next == None:
return head
# Two pointers
p = head
n = head.next
t = None
while n.next:
# If there is even element
if n.next.next:
# Keep it for now for both n and p
t = n.next.next
m = p.next
p.next = n.next
p = p.next
# Recover link for p and n
p.next = m
n.next = t
n = n.next
else:
# Save and insert odd
t = p.next
p.next = n.next
p = p.next
p.next = t
n.next = None
return head
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。