Thursday, August 4, 2011

Insert a new element in the end of Linked list

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start;
int n;
void create(struct node **, int);
void show(struct node *);
void insert_end(struct node **);
start=NULL;
        printf("Enter the number of elements you want in your linked list :");  
        scanf("%d",&n);
        create(&start,n);
        show(start);
        insert_end(&start);
        show(start);
        getch();
}

void create(struct node **q,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
 p=(struct node *)malloc(sizeof(struct node));
 printf("Enter the %d element :",i);
 scanf("%d",&(p->data));
 p->next=NULL;
 if(*q==NULL)
    *q=p;
 else
   lst->next=p;
  lst=p;
}

void show(struct node *start)
{
printf("Entered linked list is :\n"); 
while(start!=NULL)
{
printf(" %d\n",start->data);
start=start->next;
}
}

void insert_end(struct node **q)
{
 struct node *p,*ptr;
 p=(struct node *)malloc(sizeof(struct node));
 printf("Enter the element to be inserted ");
 scanf("%d",&(p->data));
 p->next=NULL;
 if(*q==NULL)
 {
   *q=p;
 }
 else
 {
  ptr=*q;
  while(ptr->next!=NULL)
  {
   ptr=ptr->next;
  }
  ptr->next=p;
}  
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More