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
相关推荐
白如意i10 分钟前
如何在 Ubuntu 16.04 服务器上安装 Python 3 并设置编程环境
linux·python·ubuntu
繁依Fanyi22 分钟前
使用 Spring Boot + Redis + Vue 实现动态路由加载页面
开发语言·vue.js·pytorch·spring boot·redis·python·算法
鸽芷咕38 分钟前
【Python报错已解决】xlrd.biffh.XLRDError: Excel xlsx file; not supported
开发语言·python·机器学习·bug·excel
Unicorn建模1 小时前
2024“华为杯”中国研究生数学建模竞赛(E题)深度剖析|数学建模完整过程+详细思路+代码全解析
python·算法·数学建模
神奇夜光杯1 小时前
Python酷库之旅-第三方库Pandas(123)
开发语言·人工智能·python·excel·pandas·标准库及第三方库·学习与成长
zhangbin_2371 小时前
【Python机器学习】NLP信息提取——提取人物/事物关系
开发语言·人工智能·python·机器学习·自然语言处理
_.Switch2 小时前
构建现代应用的Python Serverless架构详解
运维·开发语言·python·云原生·架构·serverless·restful
offduty2 小时前
Python基础03 | 变量和函数
python
空城皆是旧梦2 小时前
python爬虫初体验(二)
爬虫·python
子非鱼9212 小时前
【JavaScript】LeetCode:41-45
开发语言·javascript·leetcode·链表·二叉树