Saturday, August 20, 2011

Insert a new element in the beggining of Linked list

//Insert a new element in the beggining 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_beg(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_beg(&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_beg(struct node **q)
{
 struct node *p;
 p=(struct node *)malloc(sizeof(struct node));
 printf("Enter the element to be inserted ");
 scanf("%d",&(p->data));
 p->next=*q;
 *q=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