[LeetCode] 86. Partition List

划分链表。题意很简单,给了一个链表和一个X,请你将链表中小于X的node和大于X的node分开,但是不能打乱node之间原本的相互顺序。比较简单,思路是设两个node,smallHead, bigHead,然后开始遍历链表,大于X和小于X的node分别加到smallHead和bigHead后面。遍历完链表之后将两个链表再连起来。注意两个链表再次连起来的方式。

时间O(n)

空间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 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/11802796.html
今日推荐