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
相关推荐
荣码12 小时前
多模态应用入门:让AI看懂图片再回答问题,我踩了4个坑
java·python
羲云网络12 小时前
GPT Image 2.6 标注引导编辑:透明 PNG、markup 请求与局部验收
图像处理·人工智能·python·api
富贵儿99812 小时前
NL2SQL 实践手记 09:答案正确以后,还能更快吗——一次可核对的 AI4DB 实验
数据库·python·sql·ai·自然语言处理·langchain
小赖同学啊12 小时前
多模态 一般组合方案
python
劲夫学编程12 小时前
leetcode: 字母异位词分组
算法·leetcode
AI创界者12 小时前
Python 进阶实战(第八十五章):基于 Redis Lua 原子租约的分布式锁、看门狗续期与本地事务表/Outbox 一致性实战
人工智能·python·aigc
wy_hhxx13 小时前
[Leetcode] 动态规划(打家劫舍、0-1背包、完全背包)
算法·leetcode·动态规划·完全背包·0-1背包
Shaoshing14 小时前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
weixin_3077791314 小时前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
benchmark_cc14 小时前
如何用 Python 计算盈亏痛苦比(Gain-to-Pain Ratio)?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash