Implement Stack Using Linked List - The Coding Shala
Home >> Data Structures >> Implement Stack using Linked List
Other Posts You May Like
In this post, we will learn how to Implement Stack Using Linked List and will write a Java Program for the same.
Implement Stack using Linked List
We will implement Stack operations using LinkedList. If we implement using a linked list then the stack can grow and shrink dynamically but it requires extra memory because of pointers involvement.
Java Program:
class MyStack { Node root; //linked list node class Node { int data; Node next; Node(int data) { this.data = data; } } boolean isEmpty() { return root == null; } void push(int x) { Node newNode = new Node(x); //if stack is empty //make this as root node if(root == null) { root = newNode; } else { //add new Node at the head Node tmp = root; newNode.next = tmp; root = newNode; } } int pop() { int res = -1; if(root == null) { //empty stack; return -1; } else { res = root.data; root = root.next; } return res; } int peek() { if (root == null) { //stack underflow return -1; } else { int x = root.data;; return x; } } }
- Implement Stack using Array
- Stack Data Structure
- Java Stack
- Simple XML Validator
- Introduction to Array
Comments
Post a Comment