C Stack Using Linked list

Summary: in this tutorial, you will learn how to implement stack data structure using a linked list.

If you don’t know anything about the stack data structure, you can follow the stack implemented using an array tutorial.

The disadvantage of a stack implemented using an array is that its size is fixed and needs to be specified at compile time. This stack implementation is often impractical. To make the size of the stack to be dynamic and determined at run-time, we need to implement it using a linked list. By doing this, the size of the stack can shrink or grow on demand during the program execution. A stack implemented using a linked list is also known as a linked stack.

First, we declare the element of the stack:

Second, we need to initialize the stack by setting the head pointer of the stack to NULL:

c linked stack init

Third, to push an element into the stack, we create a new node, and point the stack pointer to the new node e.g., to push the first element:

C Linked Stack - Push the first element to stack

 

To push the second element:

C Linked Stack - push the second element to the stack

 

To pop an element from the stack, we need to get the data of the element, point the stack pointer to the next element and remove it. The following picture illustrates how to pop the top element ( 5) from the stack.

C Linked Stack - pop an element from the stack

To display the stack content, we traverse the stack elements from the first element to NULL.

Putting it all together.

Linked stack header file (stack.h)

Linked stack source code file (stack.c)

Linked stack test program:

The output of the program:

You can download the C stack implementation using a linked list via the following download link:

C Stack Using Linked List (16.1 kB) 645 downloads

In this tutorial, you have learned how to implement the stack data structure using a linked list in C.