leetcode328. Odd Even Linked List

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.

给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。

第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。

请注意,偶数组和奇数组内部的相对顺序应该与输入时保持一致。

你必须在 O(1) 的额外空间复杂度和 O(n) 的时间复杂度下解决这个问题。

思路:

如果是空链表,evenList 的初始节点就不存在,因此特殊处理,直接返回;

初始化奇数索引节点链表oddList初始化为头节点,偶数索引节点链表evenList初始化为次节点;

记录偶数索引节点链表头节点 evenList,用于之后的拼接;【奇数索引节点的头节点就是 head,不需要在额外记录了】

更新奇偶索引链表的节点;

最后一个奇数索引节点和首个偶数索引节点拼接起来;

返回头节点 head;

python 复制代码
class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head: return head   # 空链表,直接返回
        odd_list = head          # 奇数索引节点链表odd_list初始化为头节点
        even_list = head.next    # 偶数索引节点链表even_list初始化为次节点
        even_head = even_list     # 记录偶数索引节点链表头节点
        # 当前偶数节点不为空且当前偶数节点之后还有节点
        while even_list and even_list.next:
            odd_list.next = even_list.next     # 下一个奇数索引节点是当前偶数索引节点的下一个节点
            odd_list = odd_list.next            # 更新当前奇数索引节点
            even_list.next = odd_list.next     # 下一个偶数索引节点是新的奇数索引节点的下一个节点
            even_list = even_list.next          # 更新偶数索引节点
        odd_list.next = even_head   # 最后一个奇数索引节点和首个偶数索引节点拼接起来
        return head
相关推荐
Swift社区3 分钟前
Swift 图论实战:DFS 算法解锁 LeetCode 323 连通分量个数
算法·swift·图论
<但凡.6 分钟前
数据结构与算法之美:广义表
数据结构·c++·算法
前端极客探险家17 分钟前
告别卡顿与慢响应!现代 Web 应用性能优化:从前端渲染到后端算法的全面提速指南
前端·算法·性能优化
程序员Xu1 小时前
【OD机试题解法笔记】连续出牌数量
笔记·算法·深度优先
CoovallyAIHub1 小时前
单目深度估计重大突破:无需标签,精度超越 SOTA!西湖大学团队提出多教师蒸馏新方案
深度学习·算法·计算机视觉
CoovallyAIHub1 小时前
从FCOS3D到PGD:看深度估计如何快速搭建你的3D检测项目
深度学习·算法·计算机视觉
偷偷的卷2 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
北京地铁1号线2 小时前
Zero-Shot(零样本学习),One-Shot(单样本学习),Few-Shot(少样本学习)概述
人工智能·算法·大模型
凤年徐2 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal2 小时前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法