[LeetCode] Sort Linked List Already Sorted Using Absolute Values

2046. Sort Linked List Already Sorted Using Absolute Values

Given the head of a singly linked list that is sorted in non-decreasing order using the absolute values of its nodes, return the list sorted in non-decreasing order using the actual values of its nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortLinkedList(ListNode* head) {
ListNode* dummy = new ListNode(-1, head);
ListNode* runner = head->next, *last = head;

while(runner) {
ListNode* next = runner->next;
if(runner->val < 0) {
runner->next = dummy->next;
dummy->next = runner;
last->next = next;
} else last = runner;

runner = next;
}

return dummy->next;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/10/PS/LeetCode/sort-linked-list-already-sorted-using-absolute-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.