共计 786 个字符,预计需要花费 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 notthe value in the nodes.You should try to do it in place. The program should run in O(1) spacecomplexity 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