This program demonstrates the implementation of a stack data structure using a linked list. Stacks are a type of data structure with Last In First Out (LIFO) access policy. The operations demonstrated in this stack are:

  • Push: Add an item to the top of the stack.
  • Pop: Remove the item at the top of the stack.
  • Peek: Get the item at the top of the stack without removing it.
  • is_empty: Check if the stack is empty.

Code Explanation

The stack functionality is encapsulated within a class Stack. This class uses an inner class Node, which represents an element in the stack. Here’s a detailed breakdown of the methods within the Stack class:

  1. Node class: A simple class for storing data and the link to the next node.
  2. __init__: Initializes the stack.
  3. push: Adds a new element to the top of the stack.
  4. pop: Removes the element from the top of the stack and returns it.
  5. peek: Returns the top element without removing it.
  6. is_empty: Returns True if the stack is empty, otherwise False.

Python Code

class Stack:
    class Node:
        def __init__(self, value):
            self.value = value
            self.next = None

    def __init__(self):
        self.top = None

    def push(self, item):
        new_node = self.Node(item)
        new_node.next = self.top
        self.top = new_node

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        current_top = self.top
        self.top = self.top.next
        return current_top.value

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        return self.top.value

    def is_empty(self):
        return self.top is None

Usage

To use this stack, instantiate an object of the Stack class and use the push, pop, and peek methods to manipulate it.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)