Monday, March 8, 2010

ds-insert at last, delete at last in single linked list

//insert at last, delete at last in single linked list./////
////////////////////////////////////////////////////////////
#include"stdio.h"
#include"conio.h"
#include"alloc.h"

typedef struct node
{
int data;
struct node *next;
}node;
void insert(node **,int);
void del(node **);
void play(node *);
void main()
{
struct node *first=NULL;
clrscr();
insert(&first,10);
insert(&first,20);
insert(&first,30);
insert(&first,40);
play(first);
del(&first);
printf("\nafter deletion\n");
play(first);
getch();
}
void insert(node **first,int d)
{
node *p;
node *newnode=(node *)malloc(sizeof(node));
if(newnode==NULL)
{
printf("memory overflow");
exit(0);
}
newnode->data=d;
newnode->next=NULL;
if(*first==NULL)
*first=newnode;
else{
p=*first;
while((p->next)!=NULL)
p=p->next;
p->next=newnode;
}
}
void play(node *p)
{
if(p==NULL)
printf("list is empty");

while(p!=NULL)
{
printf(" %d ",p->data);
p=p->next;
}
}

void del(node **first)
{
node *t,*p;
//node *t=(node *)malloc(sizeof(node));
if(*first==NULL) {
printf("empty list");
exit(0); }

else
{
p=*first;
//t=NULL;
while(p->next!=NULL)
{t=p;
p=p->next;
}
if(t==NULL)
(*first)->next=p->next;
else
t->next=p->next;

free(p);

}
}

No comments:

Post a Comment