Skip to content

Commit a096583

Browse files
authored
Add StackUsingLinkedList.java for #6715
1 parent f0fb971 commit a096583

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* Stack implementation using singly linked list.
3+
* Supports push, pop, peek, isEmpty, and size operations in O(1) time.
4+
*
5+
* Issue: #6715
6+
* Author: @Kamal1023
7+
*/
8+
public class StackUsingLinkedList<T> {
9+
private Node<T> top;
10+
private int size;
11+
12+
// Inner Node class
13+
private static class Node<T> {
14+
T data;
15+
Node<T> next;
16+
Node(T data) {
17+
this.data = data;
18+
this.next = null;
19+
}
20+
}
21+
22+
//Pushes an element onto the stack
23+
public void push(T data) {
24+
Node<T> node = new Node<>(data);
25+
node.next = top;
26+
top = node;
27+
size++;
28+
}
29+
30+
// Removes and returns the top element of the stack
31+
public T pop() {
32+
if (isEmpty()) throw new RuntimeException("Stack is empty");
33+
T data = top.data;
34+
top = top.next;
35+
size--;
36+
return data;
37+
}
38+
39+
/** Returns the top element without removing it */
40+
public T peek() {
41+
if (isEmpty()) throw new RuntimeException("Stack is empty");
42+
return top.data;
43+
}
44+
45+
/** Checks if the stack is empty */
46+
public boolean isEmpty() {
47+
return top == null;
48+
}
49+
50+
//Returns the number of elements in the stack
51+
public int size() {
52+
return size;
53+
}
54+
55+
// Demo/test for StackUsingLinkedList
56+
public static void main(String[] args) {
57+
StackUsingLinkedList<Integer> stack = new StackUsingLinkedList<>();
58+
stack.push(10);
59+
stack.push(20);
60+
stack.push(30);
61+
62+
System.out.println("Top: " + stack.peek()); // 30
63+
System.out.println("Size: " + stack.size()); // 3
64+
65+
while (!stack.isEmpty()) {
66+
System.out.println("Pop: " + stack.pop());
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)