forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLinkedList.java
More file actions
107 lines (96 loc) · 2.63 KB
/
StackUsingLinkedList.java
File metadata and controls
107 lines (96 loc) · 2.63 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.thealgorithms.stacks;
/**
* Stack implementation using a singly linked list.
*
* @param <T> the type of elements stored in the stack
*
* Operations:
* - push(T data): Insert an element onto the stack (O(1))
* - pop(): Remove and return the top element (O(1))
* - peek(): View the top element without removing it (O(1))
* - isEmpty(): Check if the stack is empty (O(1))
* - size(): Return the number of elements (O(1))
*/
public class StackUsingLinkedList<T> {
/** Inner class representing a node in the linked list */
private class Node {
T data;
Node next;
Node(T data) {
this.data = data;
this.next = null;
}
}
private Node top; // top of the stack
private int size; // number of elements in the stack
/** Constructor: Initializes an empty stack */
public StackUsingLinkedList() {
top = null;
size = 0;
}
/**
* Pushes an element onto the top of the stack.
* @param data element to be pushed
*/
public void push(T data) {
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
size++;
}
/**
* Removes and returns the top element of the stack.
* @return the popped element
* @throws IllegalStateException if the stack is empty
*/
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot pop.");
}
T data = top.data;
top = top.next;
size--;
return data;
}
/**
* Returns the top element without removing it.
* @return the top element
* @throws IllegalStateException if the stack is empty
*/
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot peek.");
}
return top.data;
}
/**
* Checks whether the stack is empty.
* @return true if empty, false otherwise
*/
public boolean isEmpty() {
return top == null;
}
/**
* Returns the number of elements in the stack.
* @return the size of the stack
*/
public int size() {
return size;
}
/**
* Prints the stack elements from top to bottom.
*/
public void printStack() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return;
}
Node current = top;
System.out.print("Stack (top -> bottom): ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}