Sunday 25 March 2012

Program to insert the element in linked list at last position


Program to insert the element in linked list at last position.
                             
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define null 0
void main()
{
 char c;
 int i;
 struct node
 {
  int data;
  struct node *link;
 }*temp,*start,*n,*prev;
 clrscr();
 start=null;
 for(i=0;i<=1;i++)
 {
  if(start==null)
  {
   temp=(struct node *)malloc(sizeof(struct node));
   printf("enter data:");
   scanf("%d",&temp->data);
   temp->link=null;
   start=temp;
  }
  else
  {
   while(1)
   {
    printf("press n if you not want to add another node");
    fflush(stdin);
    c=getch();
    if(c=='n'||c=='N')
     break;
    else
    {
     temp->link=(struct node*)malloc(sizeof(struct node));
     temp=temp->link;
     printf("\nenter data:");
     scanf("%d",&temp->data);
     temp->link=null;
    }
   }
  }
 }
 printf("\ntraversing\n");
 temp=start;
 while(temp->link!=null)
 {
  printf("%d\t",temp->data);
  temp=temp->link;
 }
 printf("%d",temp->data);
 printf("\ninsert a link at last position:");
 n=(struct node*)malloc(sizeof(struct node));
 printf("\nenter data for the new node:");
 scanf("%d",&n->data);
 temp->link=n;
 n->link=null;
 printf("\ntraversing\n");
 temp=start;
 while(temp->link!=null)
 {
  printf("%d\t",temp->data);
  temp=temp->link;
 }
 printf("%d",temp->data);
 getch();
}

output:
enter data:45
press n if you not want to add another node
enter data:85
press n if you not want to add another node
enter data:56
press n if you not want to add another node n
traversing:
45       85      56
insert link at last position
enter data: 78
traversing
45            85           56           78

No comments:

Post a Comment