Skip to content

Commit ce4a905

Browse files
feat:Added Stack Implementation Using LinkedList
1 parent 48e02b3 commit ce4a905

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.thealgorithms.stacks;
2+
3+
class Node<T> {
4+
T data;
5+
Node<T> next;
6+
7+
public Node(T data) {
8+
this.data = data;
9+
this.next = null;
10+
}
11+
}
12+
13+
public class StackUsingLinkedList<T> {
14+
private Node<T> top;
15+
private int size;
16+
17+
public StackUsingLinkedList() {
18+
top = null;
19+
size = 0;
20+
}
21+
22+
// Push operation
23+
public void push(T data) {
24+
Node<T> temp = new Node<>(data);
25+
temp.next = top;
26+
top = temp;
27+
size++;
28+
}
29+
30+
// Pop operation
31+
public T pop() {
32+
if (top == null) {
33+
throw new RuntimeException("Stack Underflow");
34+
}
35+
T value = top.data;
36+
Node<T> temp = top;
37+
top = top.next;
38+
temp.next = null; // help GC
39+
size--;
40+
return value;
41+
}
42+
43+
// Peek operation
44+
public T peek() {
45+
if (top == null) {
46+
throw new RuntimeException("Stack is empty");
47+
}
48+
return top.data;
49+
}
50+
51+
// Size operation (O(1))
52+
public int size() {
53+
return size;
54+
}
55+
public boolean isEmpty() {
56+
return size == 0;
57+
}
58+
}
59+
class demo{
60+
public static void main(String[] args) {
61+
StackUsingLinkedList<Integer> stack = new StackUsingLinkedList<>();
62+
63+
System.out.println("Is stack empty? " + stack.isEmpty());
64+
System.out.println("Initial size: " + stack.size());
65+
66+
67+
stack.push(10);
68+
stack.push(20);
69+
stack.push(30);
70+
71+
System.out.println("After pushes:");
72+
System.out.println("Top element: " + stack.peek()); // 30
73+
System.out.println("Size: " + stack.size()); // 3
74+
75+
// Pop elements
76+
System.out.println("Popped: " + stack.pop()); // 30
77+
System.out.println("Popped: " + stack.pop()); // 20
78+
79+
System.out.println("After pops:");
80+
System.out.println("Top element: " + stack.peek()); // 10
81+
System.out.println("Size: " + stack.size()); // 1
82+
83+
System.out.println("Is stack empty? " + stack.isEmpty());
84+
85+
86+
stack.pop();
87+
System.out.println("Is stack empty after final pop? " + stack.isEmpty());
88+
}
89+
}

0 commit comments

Comments
 (0)