Implement Stack using LinkedList
Logic - Have a top node in the starting.
Insert element in Linked List at the start so latest element will be present at the top.
When we have to remove, remove the element from the top LIFO (Last In First Out).
public class StackUsingLinkedList {
private class Node {
Integer data;
Node next;
}
Node top;
public StackUsingLinkedList() {
top = null;
}
public void push(Integer element) {
Node temp = new Node();
temp.data = element;
temp.next = top;
top = temp;
}
public void pop() {
if (top == null) {
System.out.println("Stack Underflow");
}
if (top != null) {
top = top.next;
}
}
public int peek() {
// check for empty stack
if (top != null) {
return top.data;
} else {
System.out.println("Stack is empty");
return -1;
}
}
public void display() {
if (top == null) {
System.out.println("Stack Underflow");
}
Node temp = top;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
}
Comments
Post a Comment