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
相关推荐
AC赳赳老秦10 分钟前
政企内网落地:OpenClaw 离线环境深度适配方案,无外网场景下本地化模型对接与全功能使用
java·大数据·运维·python·自动化·deepseek·openclaw
星越华夏24 分钟前
python 将相对路径变成绝对路径
python
l1t27 分钟前
mingw和Linux中的gcc和llvm编译器编译的pocketpy执行同一个python脚本的不同效果
linux·运维·python
砚底藏山河38 分钟前
股票数据API接口:如何获取股票历历史分时KDJ数据
java·python·maven
web3.088899942 分钟前
天猫API接口详解:商品详情与关键词搜索商品指南及代码示例
python·json
Csvn1 小时前
Python 性能优化与 Profiling 工具
后端·python
zjy277771 小时前
c++如何实现日志文件的异步落盘功能_基于无锁队列方案【附代码】
jvm·数据库·python
Irene19911 小时前
PyCharm 大数据开发快速上手指南(类比 VSCode 、Oracle SQL Developer)
python
wang3zc1 小时前
JavaScript中函数声明位置对解析器预编译的影响
jvm·数据库·python
小白学大数据1 小时前
JS 混淆加密下的 Python 爬虫解决方案
javascript·爬虫·python