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

 Live Demo

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()); }
Updated on: 2019-07-30T22:30:24+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements