A stack is a data structure that follows the last-in, first-out (LIFO) principle, where the most recently added element is the first one to be removed. A stack can be implemented using a linked list, where the top element of the stack is the head of the linked list.
Here is an example of how you might implement a stack using a linked list in Java:
public class Stack { // Inner class to represent a node in the linked list private static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } // Head of the linked list private Node head; // Push a new element onto the stack public void push(int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; } // Pop the top element from the stack public int pop() { if (head == null) { throw new EmptyStackException(); } int data = head.data; head = head.next; return data; } // Check if the stack is empty public boolean isEmpty() { return head == null; } }
This implementation of a stack uses a linked list to store the stack elements. The push
method adds a new element to the top of the stack by setting it as the head of the linked list, and the pop
method removes the top element by updating the head of the linked list. The isEmpty
method checks if the stack is empty by checking if the head of the linked list is null
.
You can use this stack implementation in the same way you would use any other stack, by calling the push
, pop
, and isEmpty
methods as needed.