Here, i am going to implement the stack using linked list. The linked list implementation of stack can grow and shrink according to the needs at runtime. To implement stack using linked list needed an extra memory due to involvement of pointers.
See the following code to implement the stack using linked list in java:-
public class StackUsingLinkedListTest {
public static void main(String[] args) {
StackUsingLinkedList stack = new StackUsingLinkedList();
System.out.println("Stack Size: "+stack.getSize());
stack.push(10);
stack.push(20);
stack.push(30);
// stack.push(40);
System.out.println("Stack Size: "+stack.getSize());
System.out.println(stack.pop());
System.out.println("Stack Size: "+stack.getSize());
System.out.println(stack.peek());
System.out.println("Stack Size: "+stack.getSize());
}
}
public class StackUsingLinkedList {
Node head;
int size = 0;
int capacity=0;
public StackUsingLinkedList() {
this.capacity = 3;
}
public StackUsingLinkedList(int capacity) {
this.capacity = capacity;
}
public void push(int data) {
if(size == capacity) {
throw new RuntimeException("Stack Overflow");
}
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
size++;
}
public int pop() {
if(size == 0) {
throw new RuntimeException("Stack Underflow");
}
int data = head.data;
head = head.next;
size--;
return data;
}
public int peek() {
if(size == 0) {
throw new RuntimeException("Stack Underflow");
}
return head.data;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
if(size > 0) {
return true;
}
return false;
}
}
Output:-
Stack Size: 0
Stack Size: 3
30
Stack Size: 2
20
Stack Size: 2