From 37dca0af20dba335d0c4484d995b55b68fb2507e Mon Sep 17 00:00:00 2001 From: Archiita Date: Sat, 19 Oct 2019 00:34:39 +0530 Subject: [PATCH] Reversing a linked list in cpp --- .../Linked List/Sorting_linked_list.cpp | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Data Structures/Linked List/Sorting_linked_list.cpp diff --git a/Data Structures/Linked List/Sorting_linked_list.cpp b/Data Structures/Linked List/Sorting_linked_list.cpp new file mode 100644 index 0000000..c65c03b --- /dev/null +++ b/Data Structures/Linked List/Sorting_linked_list.cpp @@ -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)); +}