Insertion function is called push. And deletion of data is called pop. In a stack we can insert and delete data from only one side. Here all the data should belong to the same datatype. Peak/top-it will give the topmost element from the stack is empty()-checks if the stack is empty is full()-checks if the stack is full.
Uses of stack
reverse a string
undo
recursion/function call
to check the balance of the parenthesis
infix to prefix/postfix
To push
void push(){
int N=5;
int stack[N];
int top=-1;
int x;
printf("Enter data:");
scanf("%d",&x);
if(top==N-1){
printf("Overflow");
}
else{
top++;
stack[top]=x;
}
}
To Pop (removes the topmost item in a stack)
void pop(){
int item;
if(top==-1){
item=stack[top];
top--;
}
printf("%d",item);
}
Peek- It tells you the topmost element of the stack without removing the element or popping it.
void peek(){
if(top==-1){
//fake
}
else{
printf("%d",stack[top]);
}
}
Display- It continuously displays the element of teh stack without removing it.
void display(){
int i;
for(i=top;i>0;i--){
printf("%d",stack[i]);
}
}
Stack with linked list- In a stack with linked list it contains a stack with linked list within.
Q. Push, display, peek, pop function using stack linked list.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head,*newnode,*temp,*top,*shed;
int count=0;
void push(int x){
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=x;
newnode->next=top;
top=newnode;
}
void display(){
temp=top;
if(top==0){
//ntg
}
else{
while(temp!=0){
printf("%d",temp->data);
temp=temp->next;
}
}
}
void peek(){
if (top==0){
//empty
}
else{
printf("Top element is %d",top->data);
}
}
void pop(){
temp=top;
printf("poped element is=%d",temp->data);
top=temp->next;
free(temp);
}
void main(){
push(2);
push(8);
push(3);
push(6);
push(3);
display();
pop();
}
Hope you learnt something new about stacks.
Happy coding…