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
相关推荐
l1258655 分钟前
# RAG向量数据库优化实战:HNSW索引调参与生产级性能设计
数据库·python·mysql·langchain
meilindehuzi_a1 小时前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
Zane19941 小时前
调用了 async 函数却没执行?一文讲透协程、event loop 与 await
后端·python
OPEN-F1 小时前
Python进阶教程:装饰器与生成器深入
开发语言·python
zhipujiaoyu1 小时前
2026年大数据专科何去何从?就业前景、发展趋势全揭秘!
大数据·python
l1258652 小时前
# RAG噪声知识库治理:一致性与可信度的四层防线设计
数据库·人工智能·python·自然语言处理·langchain
zoujiahui_20182 小时前
别再只写 np.random.seed() 了:default_rng 与 np.random、random 到底差在哪?
python
Patrick在香港2 小时前
Claude Agent 进阶:4 种工具调用编排模式,让 0820 那 13 个 endpoint 并行起来
python·ai·ai编程
qq_513728042 小时前
StaleElementReferenceException(陈旧元素引用异常)
python
千里码aicood3 小时前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python