Showing posts with label Program : Singly Linked List – Sorting. Show all posts
Showing posts with label Program : Singly Linked List – Sorting. Show all posts

Monday 2 April 2012

Program : Singly Linked List – Sorting


Program : Singly Linked List – Sorting

// Sorting a linked list in ascending order

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

struct link
{
          int no;
          struct link *next;
};

struct link *node,*start,*new1,*counter;
int i,temp;

void create_link(struct link *node);
void display(struct link *node);
void sort(struct link *node);
void main()
{
          int ch;
          clrscr();
          node=(struct link *)malloc(sizeof(struct link));
          printf("\n create linked list");

          create_link(node);

          printf("\n List before Sorting");
          display(node);

          sort(node);

          printf("\n List after sorting");
          display(node);
          getch();
}

void create_link(struct link *node)
{
          char ans;
          i=0;
          start->next=NULL;
          node=start;
          printf("\n Enter 'n' for break:-");
          ans=getchar();
          while(ans!='n')
          {
                   node->next=(struct link *)malloc(sizeof(struct link));
                   node=node->next;
                   printf("\n Enter data for node:-");
                   scanf("%d",&node->no);
                   node->next=NULL;
                   fflush(stdin);
                   printf("\n Enter 'n' for break:-");
                   ans=getchar();
                   i++;
          }
}

void display(struct link *node)
{
          node=start->next;
          while(node)
          {
                   printf("\n  %d",node->no);
                   node=node->next;
          }

}
void sort(struct link *node)
{

  for(;new1->next!=NULL;new1=new1->next)
   {
      for(counter=new1->next;counter!=NULL;counter=counter->next)
          {
            if(new1->no > counter->no)
              {
                   temp=new1->no;
                   new1->no=counter->no;
                   counter->no=temp;
              }
           }
  }

}

Posted By : Ruchita Pandya