Skip to content

Commit 2d682d3

Browse files
authored
Create 2046-sort-linked-list-already-sorted-using-absolute-values.js
1 parent d3ee6ec commit 2d682d3

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
* @return {ListNode}
11+
*/
12+
const sortLinkedList = function(head) {
13+
if(head == null) return head
14+
const dummy = new ListNode(null, head)
15+
let pre = dummy, cur = head
16+
while(cur) {
17+
if(cur.val < 0 && cur !== head) {
18+
const tmp = cur.next, tmpHead = dummy.next
19+
dummy.next = cur
20+
cur.next = tmpHead
21+
pre.next = tmp
22+
cur = tmp
23+
} else {
24+
pre = cur
25+
cur = cur.next
26+
}
27+
}
28+
29+
return dummy.next
30+
};

0 commit comments

Comments
 (0)