当前位置:网站首页>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;
}
}
边栏推荐
- 安装gstreamer开发依赖库到项目sysroot目录
- How to use repeating-linear-gradient
- 讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
- MySql的安装配置超详细教程与简单的建库建表方法
- 【Star项目】小帽飞机大战(八)
- 解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie
- 【云原生】-Docker安装部署分布式数据库 OceanBase
- 【TA-霜狼_may-《百人计划》】美术2.3 硬表面基础
- leetcode 406. Queue Reconstruction by Height
- js原型详解
猜你喜欢
Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
简单谈谈Feign
小实战项目之——吃货联盟订餐系统
Project exercise - memorandum (add, delete, modify, check)
双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分
把 VS Code 当游戏机
tidyverse笔记——dplyr包
【科普向】5G核心网架构和关键技术
Bulk free text translation
【云原生】3.3 Kubernetes 中间件部署实战
随机推荐
在 ASP.NET Core 应用程序启动时运行代码的 3 种方法
Gradle remove dependency demo
Automatic translation software - batch batch automatic translation software recommendation
Moment.js common methods
2022.7.29 Array
Kubernetes调度
快速傅里叶变换(FFT)
2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
强化学习科研知识必备(数据库、期刊、会议、牛人)
【解决】npm ERR A complete log of this run can be found in npm ERR
《白帽子说Web安全》思维导图
从 Google 离职,前Go 语言负责人跳槽小公司
Koa框架的基本使用
事务的传播机制
安装gstreamer开发依赖库到项目sysroot目录
Chapter 17: go back to find the entrance to the specified traverse, "ma bu" or horse stance just look greedy, no back to search traversal, "ma bu" or horse stance just look recursive search NXM board
LeetCode刷题——摆动序列#376#Medium
Log4net 思维导图
知识、创新、回报。
拓扑排序的两种方法 --- dfs+Kahn