[LeetCode] 328. 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 on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Constraints:

  • n == number of nodes in the linked list
  • 0 <= n <= 104
  • -106 <= Node.val <= 106

奇偶链表。

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/odd-even-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

注意不是按照 node.val 而是按照 node 的顺序来做。没什么好解释的,看懂代码,思路也就看懂了。

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val) {
 4  *     this.val = val;
 5  *     this.next = null;
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @return {ListNode}
11  */
12 var oddEvenList = function(head) {
13     // corner case
14     if (head === null || head.next === null) {
15         return head;
16     }
17 
18     // normal case
19     let first = head;
20     let second = head.next;
21     let secondHead = second;
22     while (second !== null && second.next !== null) {
23         first.next = first.next.next;
24         second.next = second.next.next;
25         first = first.next;
26         second = second.next;
27     }
28     first.next = secondHead;
29     return head;
30 };

Java实现

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode oddEvenList(ListNode head) {
11         // corner case
12         if (head == null || head.next == null) {
13             return head;
14         }
15 
16         // normal case
17         ListNode first = head;
18         ListNode second = head.next;
19         ListNode secondHead = second;
20         while (second != null && second.next != null) {
21             first.next = first.next.next;
22             second.next = second.next.next;
23             first = first.next;
24             second = second.next;
25         }
26         first.next = secondHead;
27         return head;
28     }
29 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/11796071.html