[LeetCode] 86. Partition List

Divide the list. Meaning of the questions is very simple, gave a list and a X, you will separate node in the list is less than X, and X is greater than the node, but not upset the original order between each other node. Is relatively simple, the idea is to set two node, smallHead, bigHead, and then traversing the linked list, is greater than X and less than the Node X and later are applied smallHead bigHead. After completion of traversing the list again to link the two lists. Note way to link two lists again.

Time O (n)

Space O (1)

 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  * @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 smallHead = new ListNode(0);
21     let bigHead = new ListNode(0);
22     let small = smallHead;
23     let big = bigHead;
24     while (head !== null) {
25         let temp = new ListNode(head.val);
26         if (head.val < x) {
27             small.next = temp;
28             small = small.next;
29         } else {
30             big.next = temp;
31             big = big.next;
32         }
33         head = head.next;
34     }
35     small.next = bigHead.next;
36     return smallHead.next;
37 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11802796.html