Algorithm


Stack Implementation (Using Linked List):

  1. Define a Node structure with two fields:
    1. data: To store the value of the node.
    2. next: To store the reference to the next node.
  2. Initialize a pointer top to null to represent the top of the stack.
  3. Define the following operations:
    1. Push: Add an element to the stack.
      1. Create a new node and set its data to the element to be added.
      2. Set the next of the new node to the current top.
      3. Update top to point to the new node.
    2. Pop: Remove the top element from the stack.
      1. Check if the stack is empty. If top == null, display an underflow error.
      2. Otherwise, store the data of the current top node.
      3. Update top to point to top.next.
      4. Delete the old top node and return the stored data.
    3. Peek: Retrieve the top element without removing it.
      1. Check if the stack is empty. If top == null, display an error.
      2. Otherwise, return the data of the top node.
    4. IsEmpty: Check if the stack is empty by verifying if top == null.

Example:

Consider a stack implemented using a linked list. Perform the following operations:

  • Push 10, 20, 30
  • Pop an element
  • Peek the top element

After these operations, the stack will contain [10, 20], and the top element will be 20.