Doubly Linked List Program in C
Doubly Linked List Program in C
http://www.tutorialspoint.com/data_structures_algorithms/doubly_linked_list_program_in_c.htm
Copyright © tutorialspoint.com
Doubly Linked List is a variation of Linked list in which navigation is possible in both ways either
forward and backward easily as compared to Single Linked List.
Implementation in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
int length(){
int length = 0;
struct node *current;
return length;
}
while(ptr != NULL){
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
while(ptr != NULL){
//print data
printf("(%d,%d) ",ptr->key,ptr->data);
printf(" ]");
}
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()){
//make it the last link
last = link;
}else {
//update first prev link
head->prev = link;
}
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()){
//make it the last link
last = link;
}else {
//make link a new last link
last->next = link;
//mark old last node as prev of new link
link->prev = last;
}
head = head->next;
//return the deleted link
return tempLink;
}
last = last->prev;
if(current->next == NULL){
return NULL;
}else {
//store reference to current link
previous = current;
return current;
}
//create a link
struct node *newLink = (struct node*) malloc(sizeof(struct node));
newLink->key = key;
newLink->data = data;
if(current == last) {
newLink->next = NULL;
last = newLink;
}else {
newLink->next = current->next;
current->next->prev = newLink;
}
newLink->prev = current;
current->next = newLink;
return true;
}
main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);
printf("\n");
printf("\nList (Last to first): ");
displayBackward();
If we compile and run the above program then it would produce following result −
Output
List (First to Last):
[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]