
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement a Stack from a LinkedList in Java
A stack can be implemented using a LinkedList by managing the LinkedList as a stack. This is done by using a class Stack which contains some of the Stack methods such as push(), top(), pop() etc.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; class Stack { private LinkedList l = new LinkedList(); public void push(Object obj) { l.addFirst(obj); } public Object top() { return l.getFirst(); } public Object pop() { return l.removeFirst(); } } public class Demo { public static void main(String[] args) { Stack s = new Stack(); s.push(5); s.push(1); s.push(3); s.push(9); s.push(7); System.out.println("The top element of the stack is: " + s.top()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The top element of the stack is: " + s.top()); } }
Output
The top element of the stack is: 7 The stack element that is popped is: 7 The stack element that is popped is: 9 The top element of the stack is: 3
Now let us understand the above program.
A class Stack is created which contains some of the Stack methods such as push(), top(), pop() etc. A code snippet which demonstrates this is as follows −
class Stack { private LinkedList l = new LinkedList(); public void push(Object obj) { l.addFirst(obj); } public Object top() { return l.getFirst(); } public Object pop() { return l.removeFirst(); } }
In the method main(), an object s is created of the class Stack. Then this is used to push elements into the stack, display the top element and pop elements from the stack. A code snippet which demonstrates this is as follows −
public static void main(String[] args) { Stack s = new Stack(); s.push(5); s.push(1); s.push(3); s.push(9); s.push(7); System.out.println("The top element of the stack is: " + s.top()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The top element of the stack is: " + s.top()); }
Advertisements