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
相关推荐
格林威10 小时前
Baumer相机轴承滚珠缺失检测:用于精密装配验证的 6 个核心算法,附 OpenCV+Halcon 实战代码!
人工智能·opencv·算法·计算机视觉·视觉检测·工业相机·堡盟相机
一起养小猫10 小时前
Flutter for OpenHarmony 实战:2048游戏算法与优化深度解析
算法·flutter·游戏
执着25910 小时前
力扣hot100 - 226、翻转二叉树
数据结构·算法·leetcode
-Try hard-10 小时前
排序和查找算法:插入排序、希尔排序、快速排序以及二分查找
数据结构·算法·排序算法
Ivanqhz10 小时前
向量化计算
开发语言·c++·后端·算法·支持向量机·rust
ffqws_10 小时前
进阶搜索:迭代加深搜索(IDS)埃及分数题解
算法·迭代加深
格林威10 小时前
相机的“对焦”和“变焦”,这二者有什么区别?
开发语言·人工智能·数码相机·opencv·算法·计算机视觉·视觉检测
LXS_35710 小时前
常用算法(下)---拷贝、替换、算术生成、集合算法
开发语言·c++·算法·学习方法
历程里程碑10 小时前
Linux19 实现shell基本功能
linux·运维·服务器·算法·elasticsearch·搜索引擎·哈希算法
鲨辣椒1008610 小时前
算法也能降低时间复杂度???—————算法延伸
数据结构·算法·排序算法