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
相关推荐
Freya冉冉3 分钟前
【PYTHON学习】推断聚类后簇的类型DAY18
python·学习·聚类
Seven9722 分钟前
剑指offer-35、数组中的逆序对
java·leetcode
成子不是橙子23 分钟前
Langchain | Ollama | Python快速上手使用LLM的DEMO
开发语言·python·langchain·ollama
熬了夜的程序员1 小时前
【LeetCode】74. 搜索二维矩阵
线性代数·算法·leetcode·职场和发展·矩阵·深度优先·动态规划
坚持编程的菜鸟1 小时前
LeetCode每日一题——矩阵置0
c语言·算法·leetcode·矩阵
虎头金猫1 小时前
我的远程开发革命:从环境配置噩梦到一键共享的蜕变
网络·python·网络协议·tcp/ip·beautifulsoup·负载均衡·pandas
壹号用户1 小时前
python学习之可迭代对象&迭代器对象
python·学习
蒋星熠1 小时前
基于深度学习的卫星图像分类(Kaggle比赛实战)
人工智能·python·深度学习·机器学习·分类·数据挖掘
虚行1 小时前
Python学习入门
开发语言·python·学习
总有刁民想爱朕ha1 小时前
Python自动化从入门到实战(23):Python打地鼠游戏开发
开发语言·python·游戏开发