Skip to content

Create absolute list sorting in LL #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
116 changes: 116 additions & 0 deletions absolute list sorting in LL
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
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<<endl;
}

// To sort a linked list by actual values.
// The list is assumed to be sorted by absolute
// values.
void sortList(Node** head)
{
// Initialize previous and current nodes
Node* prev = (*head);
Node* curr = (*head)->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;
}