-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStack.java
More file actions
68 lines (59 loc) · 1.56 KB
/
Copy pathMyStack.java
File metadata and controls
68 lines (59 loc) · 1.56 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
package basic.basic_structure;
/**
* Created by sunbo_000 on 2/10/2016.
*/
public class MyStack {
Integer max;
Object[] stack;
Integer num;
public MyStack(Integer max) {
this.stack = new Object[max];
this.max = max;
this.num = 0;
}
public static void main(String[] args) throws Exception {
MyStack myStack = new MyStack(3);
System.out.println(myStack.empty());
myStack.push(1);
myStack.push(2);
myStack.push(3);
// myStack.push(4);
System.out.println(myStack.search(3));
System.out.println(myStack.peek());
// System.out.println(myStack.num);
myStack.output();
}
public Boolean empty() {
return this.num <= 0;
}
public void push(Object o) throws Exception {
if (num >= max) throw new Exception("Stack is Full");
stack[num] = o;
num++;
}
public Object pop() throws Exception {
if (num <= 0) throw new Exception("Stack is empty");
num--;
return stack[num];
}
public Integer search(Object o) throws Exception {
if (num <= 0) throw new Exception("Stack is empty");
for (int i = 0; i < num; i++) {
if (o.equals(stack[i])) {
return num - i;
}
}
return -1;
}
public Object peek() {
if (num <= 0) return null;
else {
return stack[num - 1];
}
}
public void output() {
for (Object o : this.stack) {
System.out.println(o);
}
}
}