Skip to content

Commit 0566a4e

Browse files
committed
sort list
1 parent 227e9c2 commit 0566a4e

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* lc148 Sort list (https://leetcode.com/problems/sort-list/)
3+
* Definition for singly-linked list.
4+
* function ListNode(val) {
5+
* this.val = val;
6+
* this.next = null;
7+
* }
8+
*/
9+
/**
10+
* @param {ListNode} head
11+
* @return {ListNode}
12+
*/
13+
const merge = (head1, head2) => {
14+
let fake = new ListNode(null), head = fake;
15+
16+
while (head1 !== null && head2 !== null) {
17+
if (head1.val < head2.val) {
18+
head.next = head1;
19+
head1 = head1.next;
20+
} else {
21+
head.next = head2;
22+
head2 = head2.next;
23+
}
24+
head = head.next;
25+
}
26+
27+
if (head1 !== null) {
28+
head.next = head1;
29+
}
30+
31+
if (head2 !== null) {
32+
head.next = head2;
33+
}
34+
35+
return fake.next;
36+
};
37+
38+
var sortList = function (head) {
39+
if (head === null || head.next === null) {
40+
return head;
41+
}
42+
43+
let slow = head, fast = head, prev = null;
44+
while (fast !== null && fast.next !== null) {
45+
prev = slow
46+
slow = slow.next;
47+
fast = fast.next.next;
48+
}
49+
prev.next = null;
50+
51+
const l1 = sortList(head);
52+
const l2 = sortList(slow);
53+
54+
return merge(l1, l2);
55+
};
56+

dataStructure/linkedList/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Linked List
22

3+
## Some Tips
4+
### Get the middle point of linked list
5+
Use two pointers, one slow, one fast.
36

47
## Questions
58
- [Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
9+
- [Sort List](https://leetcode.com/problems/sort-list/)

0 commit comments

Comments
 (0)