328. Odd Even Linked List
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:
![](https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg)
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
![](https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg)
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Constraints:
- The number of nodes in the linked list is in the range
[0, 104]
. -10^6 <= Node.val <= 10^6
题目大意
把所有奇数节点拼接在一起,然后再拼接上所有偶数节点。
请原地(in-place)实现,要求空间复杂度 O(1),时间复杂度 O(n)。
解题思路
- 遍历链表,用两个指针
odd
和even
分别指向奇数节点和偶数节点 - 不断地将
even.next
插入到odd
的后面 - eg:
- 1->2->3->4->5->6
- 1->3->2->4->5->6
- 1->3->5->2->4->6
代码
/**
* @param {ListNode} head
* @return {ListNode}
*/
var oddEvenList = function (head) {
if (!head) return head;
let res = new ListNode(0, head);
let odd = head;
let even = odd.next;
while (even && even.next) {
let even_next = even.next;
let odd_next = odd.next;
even.next = even_next.next;
even_next.next = odd_next;
odd.next = even_next;
odd = odd.next;
even = even.next;
}
return res.next;
};