Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active June 14, 2022 21:21
Show Gist options
  • Save dgodfrey206/c6be172e84e8f3e1cf83b30208c21038 to your computer and use it in GitHub Desktop.
Save dgodfrey206/c6be172e84e8f3e1cf83b30208c21038 to your computer and use it in GitHub Desktop.
Linked list merge sort
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include<bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next = nullptr;
ListNode(int data):val(data){}
};
ListNode*nn(int d){return new ListNode(d);}
void display(ListNode* head){
while(head){
cout<<head->val<<" ";
head=head->next;
}
cout<<'\n';
}
ListNode* merge(ListNode* left, ListNode* right) {
ListNode result(0);
ListNode* cur = &result;
while (left || right) {
if (!right) {
cur->next = nn(left->val);
left = left->next;
}
else if (!left) {
cur->next = nn(right->val);
right = right->next;
}
else if (left->val <= right->val) {;
cur->next = nn(left->val);
left = left->next;
} else {
cur->next = nn(right->val);
right = right->next;
}
cur = cur->next;
}
return result.next;
}
/*
ListNode* merge(ListNode* left, ListNode* right) {
ListNode result(0);
ListNode* cur = &result;
while (left || right) {
if (!right || (left && left->val <= right->val)) {
cur->next = nn(left->val);
left = left->next;
}
else if (!left || (right && right->val <= left->val)) {
cur->next = nn(right->val);
right = right->next;
}
cur = cur->next;
}
return result.next;
}
*/
ListNode* mergeSort(ListNode* head) {
if (!head || !head->next)
return head;
ListNode* slow = head, *fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* right = slow->next;
slow->next = nullptr;
return merge(mergeSort(head), mergeSort(right));
}
int main() {
ListNode*head=nn(5);
head->next=nn(4);
head->next->next = nn(3);
head->next->next->next = nn(2);
head->next->next->next->next = nn(1);
display(head);
head = mergeSort(head);
display(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment