Leetcode328 奇偶链表

思路:分别处理奇偶,保存奇偶的第一个和最后一个节点,注意最后链接的时候需要把偶数的next去掉再拼接不然就成环了

python 复制代码
class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head or not head.next or not head.next.next:
            return head

        first_odd = head
        first_even = head.next
        last_odd = head
        last_even = head.next
        current_node = first_even.next
        node_num = 3

        while current_node:
            next_node = current_node.next
            if node_num % 2 == 1:
                last_odd.next = current_node
                last_odd=current_node
            else:
                last_even.next = current_node
                last_even=current_node
            current_node = next_node
            node_num += 1
        last_odd.next=first_even
        last_even.next=None
        return first_odd
相关推荐
电子硬件笔记7 小时前
Python语言编程导论第七章 数据结构
开发语言·数据结构·python
HyperAI超神经8 小时前
【vLLM 学习】Prithvi Geospatial Mae
人工智能·python·深度学习·学习·大语言模型·gpu·vllm
逻极8 小时前
Python MySQL防SQL注入实战:从字符串拼接的坑到参数化查询的救赎
python·mysql·安全·sql注入
赫凯8 小时前
【强化学习】第一章 强化学习初探
人工智能·python·强化学习
Amewin8 小时前
window 11 安装pyenv-win管理不同的版本的python
开发语言·python
小鸡吃米…9 小时前
Python编程语言面试问题二
开发语言·python·面试
eve杭9 小时前
AI、大数据与智能时代:从理论基石到实战路径
人工智能·python·5g·网络安全·ai
Honmaple10 小时前
中国四级城市联动数据,包含港澳台,内含json , sql , python 脚本
python·sql·json
BoBoZz1910 小时前
Curvatures 曲率的计算、边缘曲率的调整以及曲率、颜色的映射
python·vtk·图形渲染·图形处理
LYFlied10 小时前
【每日算法】LeetCode 84. 柱状图中最大的矩形
前端·算法·leetcode·面试·职场和发展