Given the head
of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1)
extra space complexity and O(n)
time complexity.
Example 1:
Input: head = [1,2,3,4,5] Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7] Output: [2,3,6,7,1,5,4]
Constraints:
n ==
number of nodes in the linked list0 <= n <= 104
-106 <= Node.val <= 106
这题跟143. Reorder List和跟86. Partition List很类似,就是把链表按特定规则分成两组,再合并成一个新链表。题目是要求把一个链表的奇数位置的节点连在一起作为前半部分,然后再在把偶数位置的节点连在一起作为后半部分,最后把两部分连在一起形成一个重组的链表。
如何把奇偶位置的节点找出分到不同组里呢?其实很简单,就是正常遍历一个链表时增加一个计数(从1开始)变量,当计数变量为奇数就是奇数位置,反之就是偶数位置。另外再定义两个伪头节点,一个用来链接奇数位置的节点,另一个用来链接偶数位置的节点。整个链表遍历完就形成了两个链表,一个是奇数节点链表,另一个是偶数节点链表,最后把奇数节点链表的最后一个节点的next指向偶数节点链表的第一个节点(伪头的下一个节点),偶数节点链表的最后一个节点的next指向空。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
oh, eh = ListNode(-1), ListNode(-1)
cnt = 1
cur, op, ep = head, oh, eh
while cur:
if cnt & 1 == 1:
op.next = cur
op = op.next
else:
ep.next = cur
ep = ep.next
cur = cur.next
cnt += 1
op.next, ep.next = eh.next, None
return head