LeetCode 328. Odd Even Linked List - 链表(Linked List)系列题25

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 list
  • 0 <= 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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值