Implement a stack using singly linked list

Implement a stack using single linked list concept. all the single linked list operations perform based on Stack operations LIFO(last in first out) and with the help of that knowledge we are going to implement a stack using single linked list. using single linked lists so how to implement here it is linked list means what we are storing the information in the form of nodes and we need to follow the stack rules and we need to implement using single linked list nodes so what are the rules we need to follow in the implementation of a stack a simple rule that is last in first out and all the operations we should perform so with the help of a top variable only with the help of top variables are how to insert the elements let’s see



A stack can be easily implemented through the linked list. In stack Implementation, a stack contains a top pointer. which is “head” of the stack where pushing and popping items happens at the head of the list. first node have null in link field and second node link have first node address in link field and so on and last node address in “top” pointer.

The main advantage of using linked list over an arrays is that it is possible to implements a stack that can shrink or grow as much as needed. In using array will put a restriction to the maximum capacity of the array which can lead to stack overflow. Here each new node will be dynamically allocate. so overflow is not possible.

Stack Operations:

  1. Push() : Insert the element into linked list nothing but which is the top node of Stack.
  2. Pop() : Return top element from the Stack and move the top pointer to the second node of linked list or Stack.
  3. peek(): Return the top element.
  4. display(): Print all element of Stack.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to Implement a stack
//using singly linked list
#include <stdio.h>
#include <stdlib.h>
  
// Declare linked list node
  
struct Node {
    int data;
    struct Node* link;
};
struct Node* top;
  
// Utility function to add an element data in the stack
 // insert at the beginning
void push(int data)
{
    // create new node temp and allocate memory
    struct Node* temp;
    temp = (struct Node*)malloc(sizeof(struct Node));
  
    // check if stack (heap) is full. Then inserting an element would
    // lead to stack overflow
    if (!temp) {
        printf("\nHeap Overflow");
        exit(1);
    }
  
    // initialize data into temp data field
    temp->data = data;
  
    // put top pointer reference into temp link
    temp->link = top;
  
    // make temp as top of Stack
    top = temp;
}
  
// Utility function to check if the stack is empty or not
int isEmpty()
{
    return top == NULL;
}
  
// Utility function to return top element in a stack
int peek()
{
    // check for empty stack
    if (!isEmpty(top))
        return top->data;
    else
        exit(EXIT_FAILURE);
}
  
// Utility function to pop top element from the stack
  
void pop()
{
    struct Node* temp;
  
    // check for stack underflow
    if (top == NULL) {
        printf("\nStack Underflow");
        exit(1);
    }
    else {
        // top assign into temp
        temp = top;
  
        // assign second node to top
        top = top->link;
  
        // destroy connection between first and second
        temp->link = NULL;
  
        // release memory of top node
        free(temp);
    }
}
  
void display() // remove at the beginning
{
    struct Node* temp;
  
    // check for stack underflow
    if (top == NULL) {
        printf("\nStack Underflow");
        exit(1);
    }
    else {
        temp = top;
        while (temp != NULL) {
  
            // print node data
            printf("%d->", temp->data);
  
            // assign temp link to temp
            temp = temp->link;
        }
    }
}
  
// main function
  
int main(void)
{
    // push the elements of stack
    push(11);
    push(22);
    push(33);
    push(44);
  
    // display stack elements
    display();
  
    // print top elementof stack
    printf("\nTop element is %d\n", peek());
  
    // delete top elements of stack
    pop();
    pop();
  
    // display stack elements
    display();
  
    // print top elementof stack
    printf("\nTop element is %d\n", peek());
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to Implement a stack
// using singly linked list
// import package
import static java.lang.System.exit;
  
// Create Stack Using Linked list
class StackUsingLinkedlist {
  
    // A linked list node
    private class Node {
  
        int data; // integer data
        Node link; // reference variavle Node type
    }
    // create globle top reference variable
    Node top;
    // Constructor
    StackUsingLinkedlist()
    {
        this.top = null;
    }
  
    // Utility function to add an element x in the stack
    public void push(int x) // insert at the beginning
    {
        // create new node temp and allocate memory
        Node temp = new Node();
  
        // check if stack (heap) is full. Then inserting an
        //  element would lead to stack overflow
        if (temp == null) {
            System.out.print("\nHeap Overflow");
            return;
        }
  
        // initialize data into temp data field
        temp.data = x;
  
        // put top reference into temp link
        temp.link = top;
  
        // update top reference
        top = temp;
    }
  
    // Utility function to check if the stack is empty or not
    public boolean isEmpty()
    {
        return top == null;
    }
  
    // Utility function to return top element in a stack
    public int peek()
    {
        // check for empty stack
        if (!isEmpty()) {
            return top.data;
        }
        else {
            System.out.println("Stack is empty");
            return -1;
        }
    }
  
    // Utility function to pop top element from the stack
    public void pop() // remove at the beginning
    {
        // check for stack underflow
        if (top == null) {
            System.out.print("\nStack Underflow");
            return;
        }
  
        // update the top pointer to point to the next node
        top = (top).link;
    }
  
    public void display()
    {
        // check for stack underflow
        if (top == null) {
            System.out.printf("\nStack Underflow");
            exit(1);
        }
        else {
            Node temp = top;
            while (temp != null) {
  
                // print node data
                System.out.printf("%d->", temp.data);
  
                // assign temp link to temp
                temp = temp.link;
            }
        }
    }
}
// main class
public class GFG {
    public static void main(String[] args)
    {
        // create Object of Implementing class
        StackUsingLinkedlist obj = new StackUsingLinkedlist();
        // insert Stack value
        obj.push(11);
        obj.push(22);
        obj.push(33);
        obj.push(44);
  
        // print Stack elements
        obj.display();
  
        // pritn Top element of Stack
        System.out.printf("\nTop element is %d\n", obj.peek());
  
        // Delete top element of Stack
        obj.pop();
        obj.pop();
  
        // pritn Stack elements
        obj.display();
  
        // print Top element of Stack
        System.out.printf("\nTop element is %d\n", obj.peek());
    }
}

chevron_right



Output:

44->33->22->11->
Top element is 44
22->11->
Top element is 22


My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.