The Stack

This article assumes that you have already read Linked-List in C and does not provide much explanation.

A stack is a data structure where each element is stacked on top of the previous element. The last element pushed is the first element accessed. It follows the LIFO (Last-In, First-Out) architecture. In other words, you cannot access any element on the bottom without taking elements out of the top.

Structure

The structure is the same as a singly linked-list.

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

Let's name the head of our stack as TOP.

struct Node *TOP;

Operations

You can perform two operations on a stack:

  • Pushing onto the stack
  • Popping out of the stack

Pushing Onto The Stack

Pushing to the stack is the same as insert_at_beginning() from our singly linked-list.

void push(int item_to_insert) {    struct Node *new_item = (struct Node *)malloc(sizeof(struct Node));    new_item->data = item_to_insert;    new_item->next = NULL;    if (TOP == NULL) {        TOP = new_item;    } else {        struct Node *temp = TOP;        TOP = new_item;        TOP->next = temp;    }}

Popping Out Of The Stack

Popping out of the stack is just... our very simple delete_from_beginning() from our singly linked-list.

void pop() {    if (TOP == NULL)        return; // Return in case of underflow    else {        struct Node *temp = TOP;        TOP = TOP->next;        free(temp);    }}

What We Have

#include <stdlib.h>struct Node {    int data;    struct Node *next;};struct Node *TOP;void push(int item_to_insert) {    struct Node *new_item = (struct Node *)malloc(sizeof(struct Node));    new_item->data = item_to_insert;    new_item->next = NULL;    if (TOP == NULL) {        TOP = new_item;    } else {        struct Node *temp = TOP;        TOP = new_item;        TOP->next = temp;    }}void pop() {    if (TOP == NULL)        return; // Return in case of underflow    else {        struct Node *temp = TOP;        TOP = TOP->next;        free(temp);    }}

See Also