Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions Data Structures/Linked List/Sorting_linked_list.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* merge(ListNode* A, ListNode* B){
if(A == NULL){
return B;
}
if(B == NULL){
return A;
}

ListNode* head = NULL;

if(A->val < B->val){
head = A;
A = A->next;
}
else{
head = B;
B = B->next;
}

ListNode* temp = head;

while(A != NULL && B != NULL){
if(A->val < B->val){
temp->next = A;
A = A->next;
}
else{
temp->next = B;
B = B->next;
}
temp = temp->next;
}

if(A != NULL){
temp->next = A;
}
else{
temp->next = B;
}

return head;
}

ListNode* Solution::sortList(ListNode* A) {
ListNode* head = A;

if(head == NULL || head->next == NULL){
return head;
}

ListNode* start = A;
ListNode* end = A->next;

while(end != NULL && end->next != NULL){
start = start->next;
end = (end->next)->next;
}

end = start->next;
start->next = NULL;

return merge(sortList(head), sortList(end));
}