Create Stack Using Linked List

 Stacks: It is a linear data structure. Collection with access only to the last element inserted.

  • Last In First Out (LIFO)
  • Insert/push
  • Remove/Pop
  • Top
  • Make empty

A stack element can be implemented by both an array and a linked list.

How To Create Stack Using Linked List ?

#include<stdio.h>
#include<stdlib.h>

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

struct node *head = NULL;

void push(int a)
{
    struct node *new = malloc(sizeof(struct node));
    new->data = a;
    new->next = head;
    head = new;
}

void pop()
{
    struct node *temp;
    
    if(head==NULL)
    printf("Stack is empty\n");
    else{
        printf("%d\n", head->data);
        temp = head;
        head = head->next;
        free(temp);
    }
    
}

int main()
{
    push(10);
    push(20);
    push(30);
    pop();
    pop();
    push(40);
    pop();
    pop();

    return 0;
}
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment