当前位置:网站首页>2022.07.29_Daily Question
2022.07.29_Daily Question
2022-07-31 07:39: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;
// Holds the node at the even index position
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, One-way circular linked list appears (因为此时的headThe original linked list has been changed)
node1.next = temp;
node2.next = null;
return head;
}
}
边栏推荐
猜你喜欢
外贸网站优化-外贸网站优化教程-外贸网站优化软件
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism
Run the NPM will pop up to ask "how are you going to open this file?"
一文读懂 MongoDB 和 MySQL 的差异
tidyverse笔记——dplyr包
Web浏览器工作流程解析
数据库概论 - MySQL的简单介绍
双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分
批量免费文字翻译
随机推荐
2022.07.15_每日一题
从入门到一位合格的爬虫师,这几点很重要
Gradle剔除依赖演示
文件 - 07 删除文件: 根据fileIds批量删除文件及文件信息
2022.07.13_每日一题
QFileInfo常规方法
2022.07.12_每日一题
Run the NPM will pop up to ask "how are you going to open this file?"
03-SDRAM:写操作(突发)
知识、创新、回报。
外贸网站优化-外贸网站优化教程-外贸网站优化软件
服务器和客户端信息的获取
基于LSTM的诗词生成
庐山谣寄卢侍御虚舟
2022.07.18_每日一题
Kubernetes调度
Install the gstreamer development dependency library to the project sysroot directory
2022.07.24_每日一题
安装gstreamer开发依赖库到项目sysroot目录
英语翻译软件-批量自动免费翻译软件支持三方接口翻译