sharkman
sharkman

Reputation: 175

sorting a linked list in ascending order c++

So i have a singly linked list. New items are added to the front of the chain, so if you added 8,4,10 the list would be 10,4,8. Anyway, now I am trying to sort the list after the insertion is completed except I just cannot figure out how to then loop through these numbers and re-arrange them in ascending order. I'll probably take a break here and come back in a bit, hopefully that will help me figure this out.

*this is a project for school, so suggesting I use some other container is not helpful in my case except being informative as I cannot change what I am working with.

Layout of the list

struct Node
    {
      int Item;      // User data item
      Node * Succ;   // Link to the node's successor
    };

unsigned Num //number of items in the list
Node * Head //pointer to the first node

My insertion function looks like this

Node * newOne;
newOne = new (nothrow) Node;
newOne->Item = X;
newOne->Succ = NULL;

if(Head == NULL)
{
        Head = newOne;
}
else
{
        newOne->Succ = Head;
        Head = newOne;
}
Num++;

Upvotes: 0

Views: 6501

Answers (2)

Desert Ice
Desert Ice

Reputation: 4600

This can be done two ways, i am not going to post the code, but hopefully this will help you.

1. Arrange in ascending order during insertion

This involves adding the elements always in ascending order. For example if the link list is

            | 1  |

and you add 5 the new link list is

           |1|--->|5|

and if you add 3 next it should be

           |1| ---> |3| ----> |5|

This involves comparison of the new element till you find the correct position.

2. Wait till all the elements are inserted, arrange in ascending order.

This would involve using a sorting algorithm like merge sort, insertion sort, bubble sort etc on the elements of linklist.

After the sorting of the numbers is done, rewrite the linklist in the correct order.

Example:

if link list contains

        3 2 5 1 6 

After sorting through an algorithm

  1 2 3 5 6 (stored in an array)

Now loop through the link list and replace the elements in correct order.

Be careful if the nodes contain other elements, those other elements would need to be replaced too.

Note: This requires extra memory, the other way would to swap the nodes which would take longer time. Unless the link-list contains a large number of nodes(thus making memory important) or has other elements, using array would be simpler.

Upvotes: 4

Pete Becker
Pete Becker

Reputation: 76245

Sorting a singly linked list is nasty to code (unless you like linear sorts such as bubble sort or insertion sort). It's much simpler to copy the contents into a vector, sort the vector, and then rebuild the list.

Upvotes: 1

Related Questions