Implementation of stack using Linked List

amannarayanm · updated October 12, 2021 · C
#include <stdio.h>
#include <stdlib.h>

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

int isEmpty(struct node* sp){
    if(sp == NULL){
        return 1;
    }
    return 0;
}

int isFull(){
    struct node * ptr = (struct node*)malloc(sizeof(struct node));
    if(ptr == NULL){
        return 1;
    }
    return 0;
}

struct node* push(struct node *sp,int element){
    if(isFull()){
        printf("\nStack Overflow, you can't push element in stack");
    }
    else{
        struct node* ptr = (struct node*)malloc(sizeof(struct node));
        ptr->data = element;
        ptr->next = sp;
        return ptr;
    }
}

struct node* pop(struct node *sp){
    if(isEmpty(sp)){
        printf("\nStack UnderFlow!, you can't able to pop element from the stack");
    }
    else
    {
        struct node* ptr = sp;
        sp = sp->next;
        int element = ptr->data;
        printf("\n%d element poped from stack\n",ptr->data);
        return sp;
    }
}

void traversal_linkedlist(struct node* sp){
    while(sp!=NULL){
        printf("%d \n",sp->data);
        sp = sp->next;
    }
}

int peek(struct node* ptr,int position){
    if(isEmpty(ptr)){
        printf("\nStack Underflow!");
    }
    else{
        for(int i=1;i<position;i++){
            ptr = ptr->next;
        }
        return ptr->data;
    }
}

int topStack(struct node * sp){
    return sp->data;
}

int bottomStack(struct node * sp){
    while(sp->next!=NULL){
        sp= sp->next;
    }
    return sp->data;
}

int main() {
    
    struct node* top;
    top = NULL;
    top = push(top,45);
    top = push(top,34);
    top = push(top,23);
    top = push(top,87);
    
    
    traversal_linkedlist(top);
    
    // top = pop(top);
    // top = pop(top);
    
    // traversal_linkedlist(top);
    
    // printf("%d position : %d element\n",3,peek(top,3));
    
    printf("%d Top element of stack\n",topStack(top));
    printf("%d Top element of stack\n",bottomStack(top));
    
    return 0;
}

Comments

Please sign up or log in to contribute to the discussion.