Sunday 11 September 2016

Basic operations performed on a Doubly Linked List - C language //Easy to understand

//Run & Compiled on MS Visual Studio Express 2013


#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

struct node{
int data;
struct node* prv,* nxt;
}*start = NULL;

int count = 0;//Counter to count no. of nodes
void insrtbeg(int num)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
if (start == NULL)
{
newnode->data = num;
newnode->nxt = NULL;
newnode->prv = NULL;
start = newnode;
printf("\n\tNumber inserted Successfully\t\t(:(:(:");
}
else{
newnode->data = num;
newnode->nxt = start;
newnode->prv = NULL;
start->prv = newnode;
start = newnode;
printf("\n\tNumber inserted Successfully\t\t(:(:(:");
}
count++;
}
void delbeg()
{
struct node* p;
if (start == NULL)
{
printf("\n\tDeletion not possible");
exit(0);
}
else{
p = start;
start = p->nxt;
start->prv = NULL;
printf("\n\tDeleted no. is\t %d", p->data);
free(p);
}
count--;
}


void display()
{
struct node* p;
p = start;
if (start == NULL)
{
printf("\n\tList is empty !!!");
printf("\n\tTry Again ):\n");
return;
}
else{
while (p != NULL)
{
printf("\t%d", p->data);
p = p->nxt;
}
}

}
void xcount()
{

printf("\n\t No. of NODES are \t %d", count);

}

void insrtany(int num)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if (temp == NULL)
{
printf("\n\tOverflow ):):):   \t Aborting!!!");
exit(0);
}
struct node*t = start;//initializing *t
while (t->data != num && t != NULL)
{
t = t->nxt;
}
if (t == NULL)
{
printf("\n\t\tNUMBER is not available in the list");
exit(0);
}
else{
temp->nxt = t->nxt;
temp->prv = t;
temp->data = num;
t->nxt = temp;

printf("\n\tNumber inserted Successfully\t\t(:(:(:");
}
count++;

}

void main()
{
int ch, num;
while (1)
{
printf("\n\t1. Insertion\n\t2. Deletion\n\t3. Display\n\t4. No. of NODES\n\t5. Insert at any position\n\t6. Exit\n\t");
scanf("%d", &ch);
switch (ch)
{
case 1: printf("Enter the no. to insert\n\t");
scanf("%d", &num);
insrtbeg(num);
break;
case 2: delbeg();
break;
case 3:display();
break;
case 4:xcount();
break;
case 5:  printf("Enter the value to insert after the no. you want \n\t");
scanf("%d", &num);
insrtany(num);
break;
case 6: exit(0);
}


}
}

No comments:

Post a Comment

Sister's are an invaluable gift

It has been a year since I realized that, in this highly entropic universe, my sisters are the strongest and most stable place to which I be...