forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
54 lines (41 loc) · 1.23 KB
/
main.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/// Source : https://leetcode.com/problems/sort-linked-list-already-sorted-using-absolute-values/
/// Author : liuyubobobo
/// Time : 2021-10-20
#include <iostream>
using namespace std;
/// Linked List
/// Time Complexity: O(n)
/// Space Complexity: O(1)
/// 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* neg_head = nullptr, *neg_tail = nullptr;
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
while(cur->next){
if(cur->next->val < 0){
ListNode* neg_node = cur->next;
cur->next = neg_node->next;
neg_node->next = neg_head;
neg_head = neg_node;
if(neg_head->next == nullptr) neg_tail = neg_head;
}
else cur = cur->next;
}
if(!neg_head) return dummy->next;
neg_tail->next = dummy->next;
dummy->next = neg_head;
return dummy->next;
}
};
int main() {
return 0;
}