Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1603 from javiermon/148-Sort-List
Browse files Browse the repository at this point in the history
C Solution to Neetcode: 148 SortList
  • Loading branch information
a93a authored Feb 24, 2023
2 parents 06e13be + 07ed5ae commit 889bd4a
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions c/0148-Sort-List.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

struct ListNode* merge(struct ListNode *list1, struct ListNode *list2) {
struct ListNode *head, *tail;

if (!list1 || !list2) {
if (!list1) {
return list2;
}
return list1;
}

if (list1->val < list2->val) {
head = list1;
list1 = list1->next;
} else {
head = list2;
list2 = list2->next;
}
tail = head;

while (list1 && list2) {
if (list1->val < list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}

if (list1) {
tail->next = list1;
}

if (list2) {
tail->next = list2;
}

return head;
}

// Split a linked list in two halfs:
struct ListNode* split(struct ListNode* head) {
struct ListNode *slow = head, *fast = head, *prev = NULL;

while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}

prev->next = NULL;
return slow;
}

struct ListNode* sortList(struct ListNode *head) {
if (!head || !head->next) {
return head;
}

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

0 comments on commit 889bd4a

Please sign in to comment.