Search code examples
csingly-linked-list

sorting linked list simplest way


I am trying to code very basic sorting method for linked lists. I am getting unhandled exception. What is the mistake i am making? Here is my code:-

struct LinkedNode// structure for linked list
{
    int data;
    struct LinkedNode *next;
}* start = NULL;
    

following function creates a linked list

void CreateLinkedList()
{
    LinkedNode *newNode, *current;
    printf("enter 5 numbers to create linked list\n");
    for(int i=0; i<5; i++)
    {
        newNode = (struct LinkedNode *)malloc(sizeof(LinkedNode));
        scanf("%d", &newNode->data);
        newNode->next = NULL;
        if(start == NULL)
        {
            start = newNode;
            current = newNode;
        }
        else
        {
            current->next = newNode;
            current = newNode;
        }
    }
}

following function is used for sorting the linked list nodes

void SortLinkedList()
{
    struct LinkedNode *node=NULL, *temp = NULL;
    int tempvar;//temp variable to store node data
    node = start;
    temp = node->next;//temp node to hold node data and next link
    while(node != NULL && node->next != NULL)
    {
        for(int j=0; j<5; j++)//value 5 because I am taking only 5 nodes
        {
            if(node->data > temp->data)//swap node data
            {
                tempvar = node->data;
                node->data = temp->data;
                temp->data = tempvar;
            }
            temp = temp->next;
        }
        node = node->next;
    }
}

Solution

  • Try This code

    void SortLinkedList()
        {
        struct LinkedNode *node=NULL, *temp = NULL;
        int tempvar;//temp variable to store node data
        node = start;
        //temp = node;//temp node to hold node data and next link
        while(node != NULL)
        {
            temp=node; 
            while (temp->next !=NULL)//travel till the second last element 
            {
               if(temp->data > temp->next->data)// compare the data of the nodes 
                {
                  tempvar = temp->data;
                  temp->data = temp->next->data;// swap the data
                  temp->next->data = tempvar;
                }
             temp = temp->next;    // move to the next element 
            }
            node = node->next;    // move to the next node
        }
    }
    

    1 - outer while loop is use for the total number of pass that will require to sort the linked list..

    2- In second while loop we are actually comparing the data of the nodes that we want to sort