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