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
相关推荐
天使day7 小时前
FastAPI快速入门
python·fastapi
databook7 小时前
用相关性分析消除“冗余特征”
python·机器学习·scikit-learn
幻想时空8 小时前
地图数据采集
python
梦想不只是梦与想8 小时前
Python 中的类型判断方法
python·type·isinstance
alphaTao8 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
Kevin Wang7279 小时前
Nvidia-AGX-spark部署手册——课堂质量诊断(jetpack:r36)
python·docker·容器
Python私教10 小时前
Django 6.1 RC1 实测:FETCH_PEERS 两条 SQL 解决 N+1,select_related 还需要吗?
后端·python·django
玉鸯10 小时前
Agent 的任务编排:从 System Prompt 到 Hierarchical Multi-Agent
python·llm·agent
Python私教10 小时前
Django 6.0 自带 Tasks 到底能不能替代 Celery?跑完 3 组后台任务后我有答案了
后端·python·django
我的xiaodoujiao10 小时前
快速学习Python基础知识详细图文教程14--模块
开发语言·python·学习·测试工具