Home » Program To Sort The Elements Of The Singly Linked List

Program To Sort The Elements Of The Singly Linked List

by Online Tutorials Library

Program to sort the elements of the singly linked list

Explanation

In this program, we need to sort the nodes of the given singly linked list in ascending order.

Original list:

Program to sort the elements of the singly linked list

Sorted list:

Program to sort the elements of the singly linked list

To accomplish this task, we maintain two pointers: current and index. Initially, current point to head node and index will point to node next to current. Traverse through the list till current points to null, by comparing current’s data with index’s data. If current’s data is greater than the index’s data, then swap data between them. In the above example, current will initially point to 9 and index will point to 7. Since, 9 is greater than 7, swap the data. Continue this process until the entire list is sorted in ascending order.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class SortList which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail’s next will point to a newly added node. This new node will become the new tail of the list.
  4. sortList() will sort the nodes of the list in ascending order.
    1. Define a node current which will point to head.
    2. Define another node index which will point to node next to current.
    3. Compare data of current and index node. If current’s data is greater than the index’s data then, swap the data between them.
    4. Current will point to current.next and index will point to index.next.
    5. Continue this process until the entire list is sorted.
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

 Original list:   9 7 2 5 4   Sorted list:   2 4 5 7 9   

C

Output:

Original list:   9 7 2 5 4   Sorted list:   2 4 5 7 9   

JAVA

Output:

Original list:   9 7 2 5 4   Sorted list:   2 4 5 7 9   

C#

Output:

Original list:   9 7 2 5 4   Sorted list:   2 4 5 7 9   

PHP

Output:

 Original list:   9 7 2 5 4   Sorted list:   2 4 5 7 9   

Next Topic#

You may also like