Doubly Linked List Program
/*doubly linked List*/
#include
#include
#include
struct node
{
int no;
struct node *next;
struct node *prev;
}; /* delete at the given location*/
void deletenode(struct node **q,int num)
{
/*Deleting Node Strategy:
First:Check IF it is not null
if node found
check wheather
first element or last lement
then delete node
else
make copy at temp of previous node
move forward
*/
struct node *s,*temp;
s=*q;
while(s!=NULL)
{
if(s->no==num)
{
if(s==*q)
{
//Directly deal with original node and move to next
(*q)=(*q)->next;
//s->prev=NULL;
break;
}
else
{
temp->next=s->next;
s->next->prev=temp;
break;
}
if(s->next==NULL)
{ free(s);
s=temp;
break;
}
}
else
{
temp=s;
s=s->next;
}
}
}
void append(struct node **q,int num)
{
struct node *s,*newnode;
s=*q;
if(*q==NULL)
{
printf("Inserting First eeLEMENT");
*q=(struct node*)malloc(sizeof(struct node*));
(*q)->no=num;
(*q)->next=NULL;
(*q)->prev=NULL;
}
else
{
while(s->next!=NULL)
{
s=s->next;
}
newnode=(struct node*)malloc(sizeof(struct node*));
newnode->no=num;
newnode->next=NULL;
s->next=newnode;
}
}
void print(struct node *s)
{
printf("\n\tPrinting...");
while(s!=NULL)
{
printf("\t%d",s->no);
s=s->next;
}
}
void main()
{
struct node *s;
s=NULL;
clrscr();
append(&s,5);
append(&s,67);
append(&s,57);
printf("\n\tBefore");
print(s);
deletenode(&s,5);
printf("\n\tAfter...");
print(s);
getch();
}
No comments:
Post a Comment