Hi does anyone knows how to sort in link list, i already done some parts of it and its already working except for the sorting part. please help me about this sorting problem...

#include <stdio.h>
#include <stdlib.h>

struct nodeTag
{
	   int            nData;
	   struct nodeTag *pLink;
};

typedef struct nodeTag structNodeType;
typedef structNodeType *ptrNode;


void sortList(ptrNode *pFirst)
{
     /*PLEASE HELP ME IN THIS PART*/
}

void displayLinkedList(ptrNode pFirst)
{
     ptrNode pRun;
     
     pRun = pFirst; /* pRun and pFirst are assumed to be pointer 
                      types with pFirst pointing to the first 
                      node of a singly linked list */
    while (pRun != NULL)
    {
       printf("%d -> ", pRun->nData);
       pRun = pRun->pLink;
    }
    printf("NULL\n\n");
     
}

void createSingle (ptrNode *pFirst)
{
  int     nNum;
  ptrNode pNew, pTrail;

  *pFirst = NULL;
  
  printf("Input(enter -1 to stop):\n");
  
  do
  {
     scanf ("%d", &nNum);
     if (nNum != -1)
	{
        pNew = malloc(sizeof(structNodeType)); /* create the node */
        pNew->nData = nNum;
        pNew->pLink = NULL;
        
        if (*pFirst == NULL)  /* if the list empty */
           *pFirst = pNew;
        else 
           pTrail->pLink = pNew;   /* attach the node to the end of the
 list */
        pTrail = pNew;	/* pTrail points to the last node */
     }
  }while (nNum != -1);
  
}

void freeAll(ptrNode *pFirst)
/* deletes all the nodes in the linked list */
{
     ptrNode pRun = *pFirst;
     
     while ( pRun != NULL )    
     {
           *pFirst = (*pFirst)->pLink;      
           free (pRun);
           pRun = *pFirst;
     }
     
}

main()
{
  ptrNode pFirst;
  int nItem, nKey;

  createSingle (&pFirst);
  
  printf("After creation:\n");
  displayLinkedList(pFirst);
  
  sortList(&pFirst);
    
  printf("\nAfter sorting:\n");
  displayLinkedList(pFirst);
  
  freeAll(&pFirst);
 
}

Recommended Answers

All 3 Replies

Is there any example you know, that is closely match the way i plotted my code, sorry for that, i'm just not good at this, thanks

>Is there any example you know, that is closely match the way i plotted my code
All you have to do is change the names. The linked list I used is structured exactly the same way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.