EmbLogic's Blog

stack operations using link list (pass by reference)

main

#include”header.h”
int main()
{
int choice;
struct node *start;
start = (struct node *)malloc(sizeof(struct node));
start->next = NULL;
start->prev = NULL;
while(1)
{    choice = get_choice();
operation(choice,&start);
}
return 0;

}

 

FUNCTIONS DEFINITIONS

#include”header.h”
struct node *top=NULL;

int flag=0,count=0;
int get_choice()                                            //getchoice from user
{
int choice;
printf(“\n————STACK MENU————”);
printf(“\n 1. CREATE NODE”);
printf(“\n 2. PUSH”);
printf(“\n 3. POP”);
printf(“\n 4. DISPLAY”);
printf(“\n 0. EXIT”);
printf(“\n\n ENTER TOUR CHOICE\n”);
scanf(” %d”,&choice);
return choice;
}

int operation(int choice, struct node **start)                                //operations
{
switch(choice)
{    case 1 : create_node(start);
break;
case 2 : push(start);
break;
case 3 : pop(start);
break;
case 4 : display(start);
break;
case 0 : exit(0);
break;
default : printf(“\nENTER VALID OPTION”);
}

}

int create_node(struct node **start)                                    //create first node(first PUSH)
{

if(flag)
{    printf(“\n The Stack is already created.”);
}
if(flag==0)
{
struct node * new;
new=(struct node*)malloc(sizeof(struct node));
new->next=NULL;
new->prev = (*start);
(*start)->next = new;
top = new;
printf(“\nEnter the element in the node\n”);
scanf(“%d”,&(new-> info));
flag=1;
printf(“\nFirst element is pushed sucessfully”);
count=1;

}

}

int push(struct node **start)                                        //PUSH
{
if(count<10)
{    struct node *new;
new=(struct node *)malloc(sizeof(struct node));
new->next=NULL;
new->prev=top;
top->next=new;
top=top->next;
printf(“\nEnter the value of node\n”);
scanf(“%d”,&(top->info));
count++;
printf(“\n\nElement pushed successfully”);
}
else
{printf(“\nThe Stack is FULL..”);}

}

int pop(struct node **start)                                        //POP
{
int num;
if(top==(*start))
printf(“The Stack is Empty!!!”);
else
{
num=top->info;
top=top->prev;
top->next->prev=NULL;
top->next=NULL;
count–;
printf(“\nThe element popped is %d”,num);
}

}

int display(struct node **start)                                    //display
{
if(count==0)
printf(“\nThe Stack is empty”);
else
{    struct node *temp;
temp=top;
printf(“\nThe stack is –>”);
while(temp!=(*start))
{
printf(“->  %d”,temp->info);
temp=temp->prev;
}

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>