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
相关推荐
weixin_贾21 分钟前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演
张槊哲30 分钟前
函数的定义与使用(python)
开发语言·python
船长@Quant35 分钟前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
偶尔微微一笑1 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
Wendy_robot3 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.3 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
船长@Quant3 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手3 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin
liuweidong08023 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
CH3_CH2_CHO4 小时前
不吃【Numpy】版
开发语言·python·numpy