Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathNodeStack.java
More file actions
Latest commit
98 lines (88 loc) · 2.54 KB
/
Copy pathNodeStack.java
File metadata and controls
98 lines (88 loc) · 2.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
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
packagecom.thealgorithms.datastructures.stacks;
/**
* A stack implementation using linked nodes, supporting unlimited size without an ArrayList.
*
* <p>Each node in the stack contains data of generic type {@code Item}, along with references
* to the next and previous nodes, supporting typical stack operations.
*
* <p>The stack follows a Last-In-First-Out (LIFO) order where elements added last are
* removed first. Supported operations include push, pop, and peek.
*
* @param <Item> the type of elements held in this stack
*/
publicclassNodeStack<Item> {
/**
* Node class representing each element in the stack.
*/
privateclassNode {
Itemdata;
Nodeprevious;
Node(Itemdata) {
this.data = data;
this.previous = null;
}
}
privateNodehead; // Top node in the stack
privateintsize; // Number of elements in the stack
/**
* Constructs an empty NodeStack.
*/
publicNodeStack() {
head = null;
size = 0;
}
/**
* Pushes an item onto the stack.
*
* @param item the item to be pushed onto the stack
*/
publicvoidpush(Itemitem) {
NodenewNode = newNode(item);
newNode.previous = head;
head = newNode;
size++;
}
/**
* Removes and returns the item at the top of the stack.
*
* @return the item at the top of the stack, or {@code null} if the stack is empty
* @throws IllegalStateException if the stack is empty
*/
publicItempop() {
if (isEmpty()) {
thrownewIllegalStateException("Cannot pop from an empty stack.");
}
Itemdata = head.data;
head = head.previous;
size--;
returndata;
}
/**
* Returns the item at the top of the stack without removing it.
*
* @return the item at the top of the stack, or {@code null} if the stack is empty
* @throws IllegalStateException if the stack is empty
*/
publicItempeek() {
if (isEmpty()) {
thrownewIllegalStateException("Cannot peek from an empty stack.");
}
returnhead.data;
}
/**
* Checks whether the stack is empty.
*
* @return {@code true} if the stack has no elements, {@code false} otherwise
*/
publicbooleanisEmpty() {
returnhead == null;
}
/**
* Returns the number of elements currently in the stack.
*
* @return the size of the stack
*/
publicintsize() {
returnsize;
}
}