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
相关推荐
TracyCoder1238 分钟前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
aiguangyuan14 分钟前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
小小张说故事22 分钟前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python
luoluoal23 分钟前
基于python的医疗领域用户问答的意图识别算法研究(源码+文档)
python
Shi_haoliu29 分钟前
python安装操作流程-FastAPI + PostgreSQL简单流程
python·postgresql·fastapi
ZH154558913138 分钟前
Flutter for OpenHarmony Python学习助手实战:API接口开发的实现
python·学习·flutter
小宋102140 分钟前
Java 项目结构 vs Python 项目结构:如何快速搭一个可跑项目
java·开发语言·python
一晌小贪欢1 小时前
Python 爬虫进阶:如何利用反射机制破解常见反爬策略
开发语言·爬虫·python·python爬虫·数据爬虫·爬虫python
躺平大鹅1 小时前
5个实用Python小脚本,新手也能轻松实现(附完整代码)
python