CS DataStructure-Lecture 5 Doubly Linked List and Circular Doubly
CS DataStructure-Lecture 5 Doubly Linked List and Circular Doubly
0 1 k size-1
tail head size
typedef struct data{
int key;
Double Linked List
int val; Definition and operations
}info;
list->size--;
}
}
void TraverseAsStack(dlist* list,void (*visit)(info e)){
Node*tmp=list->tail;
while(tmp){ Traverse as stack and
(*visit)(tmp->data); queue
tmp=tmp->prev;
}
}
12
#include <stdio.h>
#include <stdlib.h> Full Example
#include "dlist.h"
0 1 k size-1
tail head size
Circular Doubly Linked List
• Same struct definitions and operations for Doubly linked list
• Same implementation for
• void create(dlist*);
• int isEmpty(dlist*);
• int isFull(dlist*);
• int listSize(dlist*);
void insertNode(info e,dlist*list){
How to insert
Node *n=(Node*)malloc(sizeof(Node));
n->data=e; node
n->next=NULL;
n->prev=NULL;
if(!list->head){
list->head=n;
list->tail=n;
n->next=list->head;
n->prev=list->tail;
}
else{
n->next=list->head;
n->prev=list->tail;
list->tail->next=n;
list->tail=n;
}
list->size++;
}
How to Delete
void deleteNode(info* e,dlist*list){ node
if(!list->head)printf("\n List is Empty");
else{
Node*n=list->head->next;
*e=list->head->data;
free(list->head);
list->head=n;
n->prev=list->tail;
list->size--;
}
}
void TraverseAsStack(dlist* list,void (*visit)(info e)){
Node*tmp=list->tail; Traverse as stack
int size=list->size;
and Queue
while(size){
(*visit)(tmp->data);
tmp=tmp->prev;
size--;
}
}
void TraverseAsQueue(dlist* list,void (*visit)(info e)){
Node*tmp=list->head;
int size=list->size;
while(size){
(*visit)(tmp->data);
tmp=tmp->next;
size--;
}
}
How to Destroy
void destroy(dlist*list){
the List
Node*tmp;
while(list->size){
tmp=list->head->next;
free(list->head);
list->head=tmp;
list->size--;
}
}
#include <stdio.h>
#include <stdlib.h>
#include "dlist.h" Full Example at
void display(info e){
printf(" %d %d \n",e.key,e.val);
}
user Level
int main()
{
info e;
int i=0; deleteNode(&e,&l);
dlist l; printf("\n Print List after deleteing an item \n");
create(&l); TraverseAsQueue(&l,&display);
printf("\n Print List after deleteing an item as stack\n");
while(i<4){ TraverseAsStack(&l,&display);
scanf("%d %d",&e.key,&e.val); return 0;
insertNode(e,&l); }
i++;
}
printf("\n Print List as Queue \n");
TraverseAsQueue(&l,&display);
printf("\n Print List as Stack \n ");
TraverseAsStack(&l,&display);
Full Example
at User Level