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
相关推荐
2301_765703142 分钟前
深入理解Python的if __name__ == ‘__main__‘
jvm·数据库·python
浒畔居3 分钟前
使用Docker容器化你的Python应用
jvm·数据库·python
有一个好名字12 分钟前
力扣-省份数量
python·算法·leetcode
爱学习的阿磊15 分钟前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
iAkuya17 分钟前
(leetcode)力扣100 55全排列
算法·leetcode·职场和发展
喵手19 分钟前
Python爬虫实战:论坛社区数据采集实战:从主题列表到分页回帖爬取(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·论坛社区数据采集·csv采集数据导出
工程师老罗25 分钟前
PyTorch transforms的用法
人工智能·pytorch·python
2401_8414956426 分钟前
【强化学习】REINFORCE 算法
人工智能·python·算法·强化学习·reinforce·策略梯度·蒙特卡洛
喵手33 分钟前
Python爬虫实战:构建企业级的招投标信息监控工具,多页动态数据抓取,实现去重增量更新(附SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·sqlite持久化存储·采集招投标信息·多页动态数据抓取
棱镜Coding1 小时前
LeetCode-Hot100 30.两两交换链表中的节点
算法·leetcode·链表