当前位置:网站首页>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;
}
}
边栏推荐
- SCI写作指南
- 360 push-360 push tool-360 batch push tool
- 文件 - 04 下载文件: 根据文件下载链接下载文件
- 【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
- Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
- 测试 思维导图
- Bulk free text translation
- 那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
- Database Principles Homework 3 — JMU
- 2022.07.12_每日一题
猜你喜欢

Analysis of pseudo-classes and pseudo-elements

DirectExchange交换机简单入门demo
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?

芯塔电子斩获第十一届中国双创大赛芜湖赛区桂冠

2022.07.18_每日一题

Explain the example + detail the difference between @Resource and @Autowired annotations (the most complete in the entire network)

LeetCode刷题——摆动序列#376#Medium

事务的传播机制

小实战项目之——吃货联盟订餐系统

In-depth analysis of z-index
随机推荐
leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
2022.07.15_每日一题
One of the small practical projects - food alliance ordering system
中断及pendSV
Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
服务器和客户端信息的获取
LeetCode刷题——摆动序列#376#Medium
2022.07.13_每日一题
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
Log4net 思维导图
文件 - 04 下载文件: 根据文件下载链接下载文件
QFileInfo常规方法
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
Redux state management
2022.07.26_每日一题
2022.07.12_每日一题
Some derivation formulas for machine learning backpropagation
Run the NPM will pop up to ask "how are you going to open this file?"
文件 - 03 下载文件:根据文件id获取下载链接
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例