[LeetCode] 86. Partition List

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example 1:

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

Example 2:

Input: head = [2,1], x = 2
Output: [1,2]

Constraints:

  • The number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

分隔链表。

给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

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

思路是设两个node,smallHead, bigHead,然后开始遍历链表,大于X和小于X的 node 分别加到 smallHead 和 bigHead 后面。遍历完链表之后将两个链表再连起来。注意最后需要把 bigHead 的 next 指针设置为 NULL,因为当前节点复用的是原链表的节点,而其 next 指针可能指向一个小于X的节点。

时间O(n)

空间O(1)

JavaScript实现

 1 /**
 2  * Definition for singly-linked list.
 3  * function ListNode(val, next) {
 4  *     this.val = (val===undefined ? 0 : val)
 5  *     this.next = (next===undefined ? null : next)
 6  * }
 7  */
 8 /**
 9  * @param {ListNode} head
10  * @param {number} x
11  * @return {ListNode}
12  */
13 var partition = function (head, x) {
14     // corner case
15     if (head === null || head.next === null) {
16         return head;
17     }
18 
19     // normal case
20     let pHead = new ListNode(0);
21     let p = pHead;
22     let qHead = new ListNode(0);
23     let q = qHead;
24     while (head !== null) {
25         if (head.val < x) {
26             p.next = head;
27             p = p.next;
28         } else {
29             q.next = head;
30             q = q.next;
31         }
32         head = head.next;
33     }
34     p.next = qHead.next;
35     q.next = null;
36     return pHead.next;
37 };

Java实现

 1 class Solution {
 2     public ListNode partition(ListNode head, int x) {
 3         // corner case
 4         if (head == null || head.next == null) {
 5             return head;
 6         }
 7 
 8         // normal case
 9         ListNode p = new ListNode(0);
10         ListNode pHead = p;
11         ListNode q = new ListNode(0);
12         ListNode qHead = q;
13         while (head != null) {
14             // < x成一组
15             if (head.val < x) {
16                 p.next = head;
17                 p = p.next;
18             }
19             // >= x成一组
20             else {
21                 q.next = head;
22                 q = q.next;
23             }
24             head = head.next;
25         }
26         p.next = qHead.next;
27         q.next = null;
28         return pHead.next;
29     }
30 }

LeetCode 题目总结

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