Implementation of Stack using LinkedList

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

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

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

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

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

struct node* pop(struct node *sp){
    if(isEmpty(sp)){
        printf("\nSTack Underflow!");
    }
    else{
        int element = sp->data;
        struct node* ptr = sp;
        sp = sp->next;
        free(ptr);
        printf("\nPoped Element: %d",element);
        return sp;
    }
}

int peek(struct node *sp ,int posi){
    
    struct node *ptr = (struct node*)malloc(sizeof(struct node));
    ptr = sp;
    for(int i=1;(ptr!= NULL && i<posi);i++){
        ptr = ptr->next;
    }
    if(ptr != NULL){
        int element = ptr->data;
        return element;
    }
    else{
        return -1;
    }
}

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

int main() {
    
    struct node* top;
    
    top = NULL;
    top = push(top,43);
    top = push(top,54);
    top = push(top,65);
    top = push(top,94);
    
    // top = pop(top);
    printf("\n%d position: %d element",1,peek(top,3));
    
    traversal(top);
    
    return 0;
}

Comments

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