当前位置:网站首页>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;
}
}
边栏推荐
- 2022.07.26_每日一题
- nohup原理
- 解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie
- 2022.07.29_每日一题
- 熟悉而陌生的新朋友——IAsyncDisposable
- 英语翻译软件-批量自动免费翻译软件支持三方接口翻译
- Bulk free text translation
- mysql索引失效的常见9种原因详解
- Analysis of pseudo-classes and pseudo-elements
- 03-SDRAM: Write operation (burst)
猜你喜欢
随机推荐
单点登录 思维导图
英语翻译软件-批量自动免费翻译软件支持三方接口翻译
iOS大厂面试查漏补缺
中断及pendSV
《白帽子说Web安全》思维导图
R——避免使用 col=0
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism
[PSQL] 复杂查询
基金投顾业务
leetcode 406. Queue Reconstruction by Height
codec2 BlockPool:unreadable libraries
【愚公系列】2022年07月 Go教学课程 022-Go容器之字典
SCI写作指南
Exam Questions Previous True Questions Wrong Bills [The Fourth Session] [Provincial Competition] [Group B]
Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
MySQL系列一:账号管理与引擎
2022.07.18_每日一题
Conditional statements of shell (test, if, case)
Analysis of the implementation principle and detailed knowledge of v-model syntactic sugar and how to make the components you develop support v-model
2022.07.12_每日一题