当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

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

Basic usage of Koa framework

Koa框架的基本使用

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

Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software

【网络攻防】常见的网络攻防技术——黑客攻防(通俗易懂版)

测试 思维导图

LeetCode brush # 376 # Medium - swing sequence

Analysis of pseudo-classes and pseudo-elements

电压源的电路分析知识分享
随机推荐
js原型详解
leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
HuffmanTree
【微服务】(十六)—— 分布式事务Seata
Moment.js common methods
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
拉格朗日插值及其应用
关于求反三角函数的三角函数值
iOS大厂面试查漏补缺
2.(1)栈的链式存储、链栈的操作(图解、注释、代码)
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
Gradle剔除依赖演示
线程中断方法
Kubernetes调度
Log4net 思维导图
Install the gstreamer development dependency library to the project sysroot directory
DDL+DML+DQL
Some derivation formulas for machine learning backpropagation
HighTec 的安装与配置
Kubernetes scheduling