跳至主要內容

328. 奇偶链表


328. 奇偶链表open in new window

🟠   🔖  链表  🔗 力扣open in new window LeetCodeopen in new window

题目

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:

  • The number of nodes in the linked list is in the range [0, 10^4].
  • -10^6 <= Node.val <= 10^6

题目大意

把所有奇数节点拼接在一起,然后再拼接上所有偶数节点。

请原地(in-place)实现,要求空间复杂度 O(1),时间复杂度 O(n)。

解题思路

  • 遍历链表,用两个指针 oddeven 分别指向奇数节点和偶数节点
  • 不断地将 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;
};

相关题目

题号标题题解标签难度
725分隔链表open in new window链表