/*
Name: Doubly Linked List
Description: Includes insertion deletion modules
*/
#include<stdio.h>
#include<conio.h>
struct linklist
{
int data;
struct linklist *next;
struct linklist *prev;
};
typedef struct linklist node;
void print(node *);
void print_r(node *);
node *create_node(int value,node *nxt,node *prv)
{
node *p;
p=(node*)malloc(sizeof(node));
p->data=value;
p->next=nxt;
p->prev=prv;
return p;
}
void create_list_e(int val,node **head)//Adding contents at the end
{
node *start;
if(*head==NULL)
(*head)=create_node(val,NULL,NULL);
else
{
start=(*head);
while(start->next!=NULL)
start=start->next;
start->next=create_node(val,NULL,start);
}
}
void create_list_b(int val,node **head)//Adding contents at the beginning
{
if(*head==NULL)
(*head)=create_node(val,NULL,NULL);
else
{
(*head)->prev=create_node(val,*head,NULL);
(*head)=(*head)->prev;
}
}
void print(node *head)/*Prints the contents of the linked list*/
{
node *t_head=head;
printf("\nContents\n");
while(t_head!=NULL)
{
printf("%d \t",t_head->data);
head=t_head;
t_head=t_head->next;
}
printf("\n");
print_r(head);
}
void print_r(node *head)/*Prints the reversed contents of the linked list*/
{
node *t_head=head;
printf("\nR_Contents\n");
while(t_head!=NULL)
{
printf("%d \t",t_head->data);
t_head=t_head->prev;
}
printf("\n");
}
void del_beg(node **head)/*Deleting from beginning*/
{
node *start;
if(*head==NULL)
printf("The list is empty\n");
else
{
printf("%d \t",(*head)->data);
start=*head;
(*head)=(*head)->next;
if(*head!=NULL)
(*head)->prev=NULL;
free(start);
}
}
void del_end(node **head)/*Deleting from end*/
{
node *start=*head;
if(*head==NULL)
printf("The list is empty\n");
else
{
while(start->next!=NULL)
start=start->next;
if(start->prev!=NULL)
start->prev->next=NULL;
else
(*head)=NULL;
free(start);
}
}
int main()
{
node *head=NULL;
create_list_e(1,&head);
create_list_e(2,&head);
create_list_b(0,&head);
create_list_b(-1,&head);
print(head);
del_beg(&head);
print(head);
del_end(&head);
print(head);
getche();
}
0 comments:
Post a Comment