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;
}

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment