Repository navigation
Expand file tree
/
Copy pathMyStack.java
More file actions
84 lines (64 loc) · 1.59 KB
/
Copy pathMyStack.java
File metadata and controls
84 lines (64 loc) · 1.59 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
package DSA.Stack;
import java.util.EmptyStackException;
public class MyStack<T> {
private class StackNode {
private final T data;
private StackNode next;
public StackNode(T data) {
this.data = data;
this.next = null;
}
}
private StackNode top;
private int length;
public MyStack() {
this.top = null;
this.length = 0;
}
public boolean isEmpty() {
return this.length == 0;
}
public void push(T value) {
StackNode temp = new StackNode(value);
if (this.top != null) {
temp.next = this.top;
}
this.top = temp;
this.length++;
}
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
T result = this.top.data;
this.top = this.top.next;
this.length--;
return result;
}
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return this.top.data;
}
private void printStack() {
StackNode current = this.top;
while (current.next != null) {
System.out.println(current.data);
current = current.next;
}
System.out.println(current.data);
}
public static void main(String[] args) {
MyStack ll = new MyStack();
ll.push(1);
ll.push(2);
ll.push(3);
ll.push(5);
ll.push(6);
ll.push(7);
ll.printStack();
System.out.println("pop: "+ ll.pop());
ll.printStack();
}
}