-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
53 lines (47 loc) · 1.16 KB
/
Stack.java
File metadata and controls
53 lines (47 loc) · 1.16 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
public class Stack {
private Node top;
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top;
top = newNode;
System.out.println("Pushed " + value);
}
public boolean isEmpty() {
return top == null;
}
public int pop() {
int value = top.value;
top = top.next;
System.out.println("Popped " + value);
return value;
}
public int peek() {
return top.value;
}
@Override
public String toString() {
return "TOP -> " + ((top == null) ? "[EMPTY]" : top.toString());
}
public static void main(String[] args) {
// example usage
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack);
stack.pop();
stack.pop();
System.out.println(stack);
stack.push(5);
stack.push(6);
stack.push(7);
System.out.println(stack);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack);
}
}