From 8b04d2c637d900eba8b58a07c671591d62c5fc4f Mon Sep 17 00:00:00 2001 From: vivek kumar singh <72482390+cyphon-tech@users.noreply.github.com> Date: Thu, 24 Jun 2021 10:39:47 +0530 Subject: [PATCH] Create absolute list sorting in LL --- absolute list sorting in LL | 116 ++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 absolute list sorting in LL diff --git a/absolute list sorting in LL b/absolute list sorting in LL new file mode 100644 index 0000000..c3824eb --- /dev/null +++ b/absolute list sorting in LL @@ -0,0 +1,116 @@ +/*Sort linked list which is already sorted on absolute values +Difficulty Level : Medium +Last Updated : 13 May, 2021 +Given a linked list that is sorted based on absolute values. Sort the list based on actual values. +Examples: + + +Input : 1 -> -10 +output: -10 -> 1 + +Input : 1 -> -2 -> -3 -> 4 -> -5 +output: -5 -> -3 -> -2 -> 1 -> 4 + +Input : -5 -> -10 +Output: -10 -> -5 + +Input : 5 -> 10 +output: 5 -> 10 +*/ + + +// C++ program to sort a linked list, already +// sorted by absolute values +#include +using namespace std; + +// Linked List Node +struct Node +{ + Node* next; + int data; +}; + +// Utility function to insert a node at the +// beginning +void push(Node** head, int data) +{ + Node* newNode = new Node; + newNode->next = (*head); + newNode->data = data; + (*head) = newNode; +} + +// Utility function to print a linked list +void printList(Node* head) +{ + while (head != NULL) + { + cout << head->data; + if (head->next != NULL) + cout << " -> "; + head = head->next; + } + cout<next; + + // Traverse list + while (curr != NULL) + { + // If curr is smaller than prev, then + // it must be moved to head + if (curr->data < prev->data) + { + // Detach curr from linked list + prev->next = curr->next; + + // Move current node to beginning + curr->next = (*head); + (*head) = curr; + + // Update current + curr = prev; + } + + // Nothing to do if current element + // is at right place + else + prev = curr; + + // Move current + curr = curr->next; + } +} + +// Driver code +int main() +{ + Node* head = NULL; + push(&head, -5); + push(&head, 5); + push(&head, 4); + push(&head, 3); + push(&head, -2); + push(&head, 1); + push(&head, 0); + + cout << "Original list :\n"; + printList(head); + + sortList(&head); + + cout << "\nSorted list :\n"; + printList(head); + + return 0; +} +