DATA STRUCTURES

Stack data structure using linked list in C programming with menu

Stack data structure using linked list in C programming with menu

  

// stack using linked list
#include <stdio.h>
#include <stdlib.h>


struct stackItem
{
int data;
struct stackItem *next;
};

struct stackItem *top = NULL;


void push(int value)
{
struct stackItem * node = (struct stackItem *)malloc(sizeof(struct stackItem));
node->data = value;
node->next = top;
top = node;

/*
if(top == NULL)
{
node->next = NULL;
top = node;
}
else
{
node->next = top;
top = node;
}
*/
printf("Pushing: %d. Done", node->data);
}

void display()
{
struct stackItem *c;
c = top;
if(top == NULL)
{
printf("nStack is empty");
return;
}

while(c != NULL)
{
printf("n%d", c->data);
c = c->next;
}
}//display()

int pop()
{
struct stackItem *poppednode;
int v;
if(top == NULL)
{
// Stack is empty
return -999;
}
else
{
poppednode = top;
v = poppednode->data;
top= top->next;
free(poppednode);

return v;
}
}//pop()

int peek()
{
int v;

if(top == NULL)
{
// Stack is empty
return -999;
}
else
{
v = top->data;
return v;
}
}

void deleteStack()
{
struct stackItem *c;
while(top != NULL)
{
c = top;
top = top->next;
free(c);
}
printf("nAll nodes freed...");
display();
}

void main()
{
int option, val;

do
{
printf("n *****MENU*****");
printf("n 1. PUSH");
printf("n 2. POP");
printf("n 3. PEEK");
printf("n 4. DISPLAY");
printf("n 0. EXIT");
printf("n Enter your choice: ");
scanf("%d",&option);

switch(option)
{
case 1:
printf("n Enter the value to push on Stack: ");
scanf("%d",&val);
push(val);
break;

case 2:
val = pop();

if(val!=-999)
printf("n The value popped from Stack = %d", val);
break;

case 3:
val = peek();
if(val!=-999)
printf("n The value at top of Stack = %d", val);
break;

case 4:
printf("n The contents of Stack are : n");
display();
break;

case 0:
printf("nFreeing Memory...");
deleteStack();
printf("nExiting...");
exit(0);
break;
default:
printf("nInvalid option. Try again...");
}

}while(1);

getch();
}

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button