Skip to content

Commit 11de177

Browse files
authored
Create 2046.Sort-Linked-List-Already-Sorted-Using-Absolute-Values.cpp
1 parent 74977b4 commit 11de177

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* sortLinkedList(ListNode* head)
14+
{
15+
16+
ListNode* pos = new ListNode(0);
17+
ListNode* neg = new ListNode(0);
18+
ListNode* h = head;
19+
ListNode* p1 = pos;
20+
ListNode* p2 = neg;
21+
22+
while (h)
23+
{
24+
if (h->val>=0)
25+
{
26+
p1->next = h;
27+
h = h->next;
28+
p1 = p1->next;
29+
30+
}
31+
else
32+
{
33+
p2->next = h;
34+
h = h->next;
35+
p2 = p2->next;
36+
}
37+
}
38+
p1->next = NULL;
39+
p2->next = NULL;
40+
41+
pos = pos->next;
42+
neg = neg->next;
43+
44+
neg = reverseLinkedList(neg);
45+
46+
if (neg)
47+
{
48+
h = neg;
49+
while (h->next) h = h->next;
50+
h->next = pos;
51+
return neg;
52+
}
53+
else
54+
return pos;
55+
}
56+
57+
ListNode* reverseLinkedList(ListNode* head)
58+
{
59+
ListNode* cur = head;
60+
ListNode* last = NULL;
61+
ListNode* next = NULL;
62+
while (cur!=NULL)
63+
{
64+
next = cur->next;
65+
cur->next = last;
66+
last = cur;
67+
cur = next;
68+
}
69+
return last;
70+
}
71+
};

0 commit comments

Comments
 (0)