当前位置:网站首页>2022.07.29_每日一题
2022.07.29_每日一题
2022-07-31 06:07:00 【诺.い】
328. 奇偶链表
题目描述
给定单链表的头节点 head ,将所有索引为奇数的节点和索引为偶数的节点分别组合在一起,然后返回重新排序的列表。
第一个节点的索引被认为是 奇数 , 第二个节点的索引为 偶数 ,以此类推。
请注意,偶数组和奇数组内部的相对顺序应该与输入时保持一致。
你必须在 O(1) 的额外空间复杂度和 O(n) 的时间复杂度下解决这个问题。
示例 1:

输入: head = [1,2,3,4,5]
输出: [1,3,5,2,4]
示例 2:

输入: head = [2,1,3,5,6,4,7]
输出: [2,3,6,7,1,5,4]
提示:
n ==链表中的节点数0 <= n <= 104-106 <= Node.val <= 106
coding
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode node1 = head;
ListNode node2 = head.next;
// 存放偶数索引位置的节点
ListNode temp = head.next;
ListNode cur = head.next.next;
// flag = true -> 奇数索引
boolean flag = true;
while (cur != null) {
if (flag) {
node1.next = cur;
node1 = node1.next;
} else {
node2.next = cur;
node2 = node2.next;
}
cur = cur.next;
flag = !flag;
}
// node1 -> node2
// 如果 node1.next = head.next; 会出现 Error - Found cycle in the ListNode, 出现单向环形链表 (因为此时的head原链表已经发生了改变)
node1.next = temp;
node2.next = null;
return head;
}
}
边栏推荐
- 熟悉而陌生的新朋友——IAsyncDisposable
- 试题 历届真题 错误票据【第四届】【省赛】【B组】
- Redux状态管理
- 【云原生】-Docker安装部署分布式数据库 OceanBase
- Some derivation formulas for machine learning backpropagation
- 毫米波技术基础
- 把 VS Code 当游戏机
- leetcode 406. Queue Reconstruction by Height
- leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
- Database Principles Homework 2 — JMU
猜你喜欢

数据库原理作业2 — JMU

从 Google 离职,前Go 语言负责人跳槽小公司

数据库概论 - MySQL的简单介绍

【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止

事务的传播机制

我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件

Database Principles Homework 2 — JMU

Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained

LeetCode brush # 376 # Medium - swing sequence

服务器和客户端信息的获取
随机推荐
什么是半波整流器?半波整流器的使用方法
Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
Web浏览器工作流程解析
(border-box) The difference between box model w3c and IE
一文读懂 MongoDB 和 MySQL 的差异
03-SDRAM: Write operation (burst)
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
tidyverse笔记——管道函数
Bulk free text translation
【Go语言刷题篇】Go完结篇函数、结构体、接口、错误入门学习
Some derivation formulas for machine learning backpropagation
nohup principle
codec2 BlockPool:不可读库
【解决】npm ERR A complete log of this run can be found in npm ERR
How to use repeating-linear-gradient
tidyverse笔记——dplyr包
Project exercise - memorandum (add, delete, modify, check)
【云原生】-Docker容器迁移Oracle到MySQL
强化学习科研知识必备(数据库、期刊、会议、牛人)
测试 思维导图