Data Structure - [Example of Sorted Linked List]

♠ Posted by Unknown in , at 11:37

Example of Sorted Linked List


#include<stdio.h>
#include<malloc.h>
struct link
{
   int data;
   struct link *next;
};
int i;
int number;

struct link *start, *node, *previous, *new1, *counter;


void main()
{
 link_sort();
}


//User Defined Function (UDF) to sort list
//It is only swap data instead of whole node to sort list
void link_sort()
{
  printf("\n Input the number of node we need to create:");
  scanf("%d",&number);

  start->next = NULL;
  node = start;
  for(i=0;i<number;i++)
  {
    node->next = (struct link*)malloc(sizeof(struct link));
    node = node->next;
    printf("\n Input the first node: %d; ", i+1);
    scanf("%d", &node->data);
    node->next = NULL;
  }
  for(new1 = start; new1->next != NULL; new1 = new1->next)
  {
   for(counter = new1->next; counter !=NULL; counter = counter->next)
    {
     if(new1->data > counter->data)
       {
            int temp = new1->data;
            new1->data = counter->data;
            counter->data = temp;
       }
    }
  }
  node = start->next;
  printf("\n After sorting the list is as follows:\n");
  while(node)
  {
    printf("%d", node->data);
    node = node->next;
  }
}