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
相关推荐
chengooooooo40 分钟前
leetcode Top100 238. 除自身以外数组的乘积|数组系列
算法·leetcode
Eiceblue2 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550402 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂2 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP3 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@3 小时前
Python数据分析7
开发语言·python
老胖闲聊4 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
GalaxyPokemon4 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
码界奇点4 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI4 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python