Stack Push and Pop Operation using LinkedList

Algorithm

INPUT: HEADER is a pointer to the header node of the linkedlist
OUTPUT: Prints the elements of the stack after operation
DATA STRUCTURE: Stack using Singly Linkedlist

Algo Push

STEP 1: START
STEP 2: IF(TOP=SIZE-1)THEN
STEP 3: PRINT("STACK OVERFLOWS")
STEP 4: ELSE
STEP 5: TOP=TOP+1
STEP 6: NEW=NEWNODE(NODE)
STEP 7: NEW->DATA=ITEM
STEP 8: NEW->LINK=NULL
STEP 9: PTR->LINK=NEW
STEP 10: PTR=NEW
STEP 11: END

Algo Pop

STEP 1: START
STEP 2: IF(TOP=-1)THEN
STEP 3: PRINT("STACK UNDERFLOWS")
STEP 4: ELSE
STEP 5: ITEM=NEW->DATA
STEP 6: FREE(NEW)
STEP 7: TOP=TOP-1
STEP 8: END

Code

#include <stdio.h>
 #include <stdlib.h>
 int size;
 int top=-1,item,size=4;
 int a[4],n;
 struct node {
    int data;
    struct node *link;
 };
 void newnode();
 struct node *ptr,*news,*header;
 void display();void push();void pop();
 int main()
 {    
header=malloc(sizeof(struct node));
    header->link=news;
    ptr=header;
    char ch; 
    do{
    printf("enter 1 for push operation in stack , 2 for pop operation in stack:\n");
    scanf("%d",&n);
    switch(n)
    {
        case 1:
        push();
        printf("Stack after operation\n");
        display();
        break;
        case 2:
        pop();
           printf("Stack after operation\n");
        display();
        break;
        default:
        printf("Wrong choice\n");
    }
    printf("do you want to do again?");
    scanf("%c",&ch);
    }
    while((getchar())!='n');
    display();
    printf("\n\n");
    return 0;
 }
 void push(){
    if(top==size-1)
    {printf("Stack Overflow");}
    else {
         printf("Enter the item you want to insert?\n");
        scanf("%d",&item);
    top=top+1;
    newnode();
    news->data=item;
            news->link=NULL;
            ptr->link=news;
            ptr=news;
    }
 }
 void pop()
 {
    if(top==-1)
    {
        printf("stack underflow");
    }
    else{
        item=a[top];
        top--;
    }
 }
 void newnode()
 {
    news=malloc(sizeof(struct node));
           
}
 void display()
 {
    if(top==-1)
    {
        printf("stack underflows");
    }struct node *p;
    p=header->link;
    for(int i=top;i>=0;--i)
    {
        printf("%d ",p->data);
        p=p->link;
    }
    printf("\n");
 }

Output

user@computer$ : enter 1 for push operation in stack , 2 for pop operation in stack:
1
Enter the item you want to insert?
5
Stack after operation
5
do you want to do again?y
enter 1 for push operation in stack , 2 for pop operation in stack:
1
Enter the item you want to insert?
6
Stack after operation
5 6
do you want to do again?y
enter 1 for push operation in stack , 2 for pop operation in stack:
2
Stack after operation
5
do you want to do again?n
5

Leave a Comment

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