【LeetCode】奇偶链表 [M](链表)
2023-09-27 14:19:51 时间
一、题目
给定单链表的头节点 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 <= 10^4
-10^6 <= Node.val <= 10^6
二、代码
/**
* 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 oddHead = head;
ListNode oddTail = head;
// 偶数编号的链表头尾节点
ListNode evenHead = head.next;
ListNode evenTail = head.next;
// 当前遍历到的节点
ListNode cur = head.next.next;
// 将奇偶链表都和外界断开
oddTail.next = null;
evenTail.next = null;
// 标识当前遍历到的节点编号是多少
int cnt = 3;
while (cur != null) {
// 奇数编号
if ((cnt & 1) == 1) {
// 将当前节点挂到奇数链表尾部
oddTail.next = cur;
cur = cur.next;
oddTail = oddTail.next;
oddTail.next = null;
// 偶数编号
} else {
// 将当前节点挂到奇偶数链表尾部
evenTail.next = cur;
cur = cur.next;
evenTail = evenTail.next;
evenTail.next = null;
}
// 编号+1
cnt++;
}
// 将奇数和偶数链表连在一起,奇数链表在前,偶数链表在后
oddTail.next = evenHead;
return oddHead;
}
}
三、解题思路
纯考coding能力,没有算法的东西。非常简单的一道题。
相关文章
- Leetcode: Recover Binary Search Tree
- Leetcode: Evaluate Reverse Polish Notation
- leetcode 114.Flatten Binary Tree to Linked List (将二叉树转换链表) 解题思路和方法
- 【Leetcode】234. 回文链表
- JS leetcode 检查单词是否为句中其他单词的前缀 解题分析,活用startsWith方法
- JS leetcode 反转字符串中的单词 III 题解分析
- 【python】leetcode 141. 环形链表
- [LeetCode]5397. 最简分数
- [LeetCode]11. 盛最多水的容器
- 每日leetcode算法题:1两数之和
- 【leetcode】日积月累,每日一题--203. 移除链表元素(DayDayUp 12)
- LeetCode || Palindrome Number
- 【leetcode】203:移除链表元素
- 【leetcode】141:环形链表
- 【Leetcode 】21:合并两个有序链表(Python)
- [LeetCode] 1171. Remove Zero Sum Consecutive Nodes from Linked List 从链表中删去总和值为零的连续节点
- [LeetCode] Split Array into Fibonacci Sequence 分割数组成斐波那契序列
- [LeetCode] Coin Path 硬币路径
- [LeetCode] Flatten Nested List Iterator 压平嵌套链表迭代器
- [LeetCode] 327. Count of Range Sum 区间和计数
- [LeetCode] Odd Even Linked List 奇偶链表
- [LeetCode] Delete Node in a Linked List 删除链表的节点
- [LeetCode] Basic Calculator 基本计算器
- [LeetCode] Partition List 划分链表
- [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
- [LeetCode] 114. Flatten Binary Tree to Linked List 将二叉树展开成链表
- leetcode 148. Sort List 排序链表(中等)
- leetcode 322. Coin Change 零钱兑换(中等)
- leetcode算法226.翻转二叉树
- leetcode算法83.删除排序链表中的重复元素
- leetcode算法21.合并两个有序链表