Data Structures Week 6

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

AIM: TO PERFORM STACK OPERATIONS USING LINKED LISTS.

ALGORITHM:
STEP 1: START.
STEP 2: CREATE A STRUCTURE NODE CONTAINING ELEMENTS VAL AND NEXT.
STEP 3: DEFINE A FUNCTION PUSH THAT PERFORMS PUSH OPERATION i.e
INSERTING ELEMENTS AT THE TOP OF THE STACK i.e AT END OF THE LINKED
LIST.
STEP 4: DEFINE A FUNCTION POP THTAT PERFORMS POP OPERATION i.e
DELETING THE ELEMENT AT THE TOP OF THE STACK
STEP 5: DEFINE THE FUNCTION DISPLAY TAHT PRINTS ALL THE VALUES
PRESENT IN THE STACK.
STEP 6: CALL THE FUNCTIONS USING THE SWITCH CASE AND WHILE LOOP.
STEP 7: STOP.

CODE:
#include <stdio.h>
#include <stdlib.h>
void push();
void pop();
void display();
struct node
{
int val;
struct node *next;
}*temp,*top;

void main ()
{
int choice=0;
while(choice != 4)
{
printf("\n\nChose the operation you want to perform\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
temp = malloc(sizeof(struct node));
if(temp == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(top==NULL)
{
temp->val = val;
temp -> next = NULL;
top=temp;
}
else
{
temp->val = val;
temp->next = top;
top=temp;

}
printf("Item pushed");

}
}

void pop()
{
struct node *temp;
if (top == NULL)
{
printf("The stack is empty");
}
else
{
temp = top;
top = top->next;
free(temp);
printf("Pop has been performed");

}
}
void display()
{
int i;
struct node *temp;
temp=top;
if(temp == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("The elements present in the stack are \n");
while(temp!=NULL)
{
printf("%d\n",temp->val);
temp = temp->next;
}
}
}
OUTPUT:

You might also like