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
相关推荐
用户968221618185 分钟前
python面向对象进阶
python
NeoFii9 分钟前
Day 28:类的定义和方法
python
七七软件开发1 小时前
团购商城 app 系统架构分析
java·python·小程序·eclipse·系统架构·php
七七软件开发1 小时前
打车小程序 app 系统架构分析
java·python·小程序·系统架构·交友
凹凸曼说我是怪兽y1 小时前
python后端之DRF框架(上篇)
开发语言·后端·python
_iop991 小时前
pandas实战1:淘宝用户行为分析
python
l1t1 小时前
修改DeepSeek翻译得不对的V语言字符串文本排序程序
c语言·开发语言·python·v语言
倔强青铜三2 小时前
PyCharm正在慢性死亡?VSCode碾压式逆袭!
python·pycharm·visual studio code
z樾2 小时前
Sum-rate计算
开发语言·python·深度学习
都叫我大帅哥2 小时前
决策树实战:信用卡欺诈检测全流程解析
python·机器学习