Search more programs

C Program for Doubly Linked List with Reverse Traversal

".C" file for Doubly Linked List is available in downloadable format at :



(Open the link and click on the download arrow on the top right to download the file.)

Given below is the code for "C Program for Doubly Linked List with Reverse Traversal" :


-----------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>

struct node 
{
int data;
struct node* next;
struct node* prev;
};

struct node* head; 


struct node* new_insert(int x)
{
struct node* newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->prev = NULL;
newnode->next = NULL;
return newnode;
}


void insert_at_start(int x) 
{
struct node* newnode = new_insert(x);
if(head == NULL)
{
head = newnode;
return;
}
head->prev = newnode;
newnode->next = head; 
head = newnode;
}


void insert_at_end(int x) 
{
struct node* temp = head;
struct node* newnode = new_insert(x);
if(head == NULL)
{
head = newnode;
return;
}
while(temp->next != NULL) temp = temp->next;
temp->next = newnode;
newnode->prev = temp;
}


void print()
{
struct node* temp = head;

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


void reverse_traverse()
{
struct node* temp = head;
if(temp == NULL) return;

while(temp->next != NULL)
{
temp = temp->next;
}

while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->prev;
}
printf("\n");
}

int main()
{
 int choice, x;

 head = NULL;

while(1)
{
printf("\n\n\n1. Add new data at start.\n2. Add new data at end.\n3. Display List.\n4. Traverse the list backwards.\n5. Exit program.\n\nEnter your choice:\t");
scanf("%d", &choice);

switch(choice)

{
case 1: printf("Enter data:\t"); scanf("%d", &x); insert_at_start(x); printf("The modified list is:\n"); print(); break;

case 2: printf("Enter data:\t"); scanf("%d", &x); insert_at_end(x);   printf("The modified list is:\n"); print(); break;

case 3: print(); break;

case 4: reverse_traverse(); break;

case 5: exit(0);

default: printf("\n\nHey!! Choose an option from the choices mentioned!!\n And stop testing my program!!");
}
}
 }

-----------------------------------------------------------------------

No comments:

Post a Comment