-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackPlain.java
85 lines (61 loc) · 1.29 KB
/
StackPlain.java
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
public class StackPlain {
private class Node {
public String item;
public Node next;
public Node(String item) {
this.item = item;
}
}
private int size;
private Node first;
public StackPlain() {
}
public void push(String item) {
Node oldFirst = first;
first = new Node(item);
first.next = oldFirst;
size++;
}
public String pop() {
if (isEmpty()) return null;
String item = first.item;
first = first.next;
size--;
System.out.printf("[pop] Item %s is removed from stack.\n", item);
return item;
}
public boolean isEmpty() {
return size == 0;
}
public void print() {
if (first == null) {
System.out.print("[print] Stack is empty!\n");
return;
}
System.out.printf("[print] Stack: %s", first.item);
Node next = first.next;
while (next != null) {
System.out.printf(", %s", next.item);
next = next.next;
}
System.out.print(".\n");
}
public static void main(String[] args) {
StackPlain st = new StackPlain();
st.push("1");
st.push("2");
st.print();
st.push("3");
st.print();
st.pop();
st.print();
st.push("3");
st.print();
st.pop();
st.pop();
st.pop();
st.pop();
st.pop();
st.print();
}
}