IN JAVA LANGUAGE
Linked List-Based Stack Implementation
Implement Stack using a Linked List
Instead of using an array, as the StackLab did, here you will use a Linked List from your language's library. Implement all the methods of Stack : push(), pop(), size(), printStackDown(), etc, using calls to the linked list methods that correspond to the actions need. In the array implementation, you wrote code to manipulate the array. For this linked list implementation, methods already exist.
Before the underlying implementation of stack was array, now the underlying implementation of stack will be Linked list.
Below is the stack implementation using the LinkedList Class.
import java.util.*;
//StackUsingLinkedList is the class which uses LinkedList for stack implementation
public class StackUsingLinkedList {
//LinkedList of String Object
LinkedList<String> ll;
public StackUsingLinkedList() {
ll = new
LinkedList<>();
}
//add the string object to top of the stack
public void push(String nodeValue) {
ll.addFirst(nodeValue);
}
//checks if the stack is empty
public boolean isEmpty() {
if (ll.size() == 0) {
return
true;
}
return false;
}
//prints the top of the stack and also removes it
public void pop() {
if (ll.size()==0) {
System.out.println("stack is empty");
}
else {
System.out.println(ll.getFirst());
ll.removeFirst();
}
}
//returns the top of the stack value
public String peek() {
if (ll.size()==0) {
System.out.println("stack is empty");
return "";
}
else {
return
ll.getFirst();
}
}
//deletes the stack
public void deleteStack() {
ll.clear();
}
//prints the size of stack
public int size() {
return ll.size();
}
//displays the stack from top to bottom
public void printStackDown()
{
// check for stack underflow
if (ll.size() == 0) {
System.out.println("No data in the stack");
}
else {
for (int i = 0;
i < ll.size(); i++) {
System.out.println(ll.get(i) + " ");
}
}
}
}
Below is the Main Class for testing:
public class Main{
//main method for testing
public static void main(String[] args) {
StackUsingLinkedList m = new StackUsingLinkedList();
m.push("Hi");
m.push("Hello");
System.out.println("size of stack: " + m.size());
System.out.println("printing the stack: " );
m.printStackDown();
System.out.println("pop the stack" );
m.pop();
m.push("How r
u");
System.out.println("printing the stack: " );
m.printStackDown();
System.out.println("pop the stack" );
m.pop();
System.out.println("pop the stack" );
m.pop();
System.out.println("printing the stack: " );
m.printStackDown();
System.out.println("pop the stack" );
m.pop();
}
}
Get Answers For Free
Most questions answered within 1 hours.