Sunday, March 10, 2013

Write C program to create and print Single linked list using functions


Write C program to create and print linked list using functions

struct node
{
   int data;
   struct node *link;
};

struct node * getnode()
{
  struct node *p;
  p=(struct node *)malloc(sizeof(struct node));
  printf("Enter data into the node: ");
  scanf("%d", &p->data);
  p->link=NULL;
  return p;
}


struct node * createnodes()
{
   struct node *first,*t,*temp;
   char ch='y';
   int sct=0;
    while (ch=='y')
   {
      if (sct==0)
      {
              first=getnode();
              temp=first;
              sct++;
      }
      else
      {
            temp=first;
            while(temp->link!=NULL)
            {
               temp=temp->link;
            }
            t=getnode();
            temp->link=t;
            temp=t;
      }
      printf("Do you want to continue: ");
      fflush(stdin);
      ch=getchar();
   }
   return first;
}



void slinkdisplay(struct node *first)
{
  struct node *temp;
  temp=first;
    while (temp->link!=NULL)
    {
      printf("%d --> ",temp->data);
      temp=temp->link;
    }
    printf("%d -->NULL",temp->data);
}



void main()
{
   struct node *f;
   clrscr();
   f=createnodes();
   slinkdisplay(f);
   getch();
}

No comments:

Post a Comment