/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode oddEvenList(ListNode head) { if (head == null || head.next == null) return head; ListNode even = ...
如果链表只有两个元素,则不用进入下面的核心 while 循环 even_head = even # 保存偶数位的第一个节点 while even and even.next: # 第一个奇数节点已经存在=头节点。这里确保后面存在只少2个节点。一个是偶数节点,跟着一个奇数节点 odd.next = even.next # 奇数节点跳过一个偶数节点,连接到下一个奇数节点...
(1)先递归oddEvenList(head -> next -> next),链表此时为2->1->(递归结果:3->6->7->5->4)(2)把2插入到3(递归结果奇数位的第一个位置)前面,把1插入到5前面(递归结果偶数位的第一个位置)此法缺点,每次递归都要求当前链表长度,时间复杂度肯定超O(n)了,不推荐...
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity....
LeetCode-Odd Even Linked List Description: Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) ...
https://leetcode-cn.com/problems/odd-even-linked-list/ Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. The first node is considered odd, and the second node is even, and so ...
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity...
力扣leetcode-cn.com/problems/odd-even-linked-list/ 题目描述 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为O(nodes),nodes 为节点...
用虚拟节点来简化操作循环的结束条件设置为 odd && odd.next && even && even.next, 不应该是odd && even, 否则需要记录一下奇数节点的最后一个节点,复杂了操作 代码 语言支持:JS,C++ JavaScript Code:/* * @lc app=leetcode id=328 lang=javascript * * [328] Odd Even Linked List * * *//** ...
class Solution { public ListNode oddEvenList(ListNode head) { if(head == null) return null; ListNode odd = head; ListNode even = head.next; ListNode evenHead = even; while(even != null && even.next != null){ odd.next = odd.next.next; odd = odd.next; ...