-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
63 lines (53 loc) · 1.26 KB
/
Stack.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
package algorithm.datastructure.stack;
/**
* {@index Stack implemented by array}
* <p>
* LIFO: Last In, First Out
*
* @author marvin
* @version Stack.java, v 0.1 15/02/2021 4:18 下午 $
* @link https://www.geeksforgeeks.org/stack-data-structure-introduction-program/
*/
public class Stack {
private int capacity;
private int top;
private int[] data;
private Stack() {
}
public Stack(int capacity) {
this.capacity = capacity;
data = new int[this.capacity];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1;
}
public boolean push(int item) {
if (isFull()) {
System.out.println("Stack is full");
return false;
}
data[++top] = item;
return true;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty.");
return Integer.MIN_VALUE;
}
return data[top--];
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
return data[top];
}
public int size() {
return top + 1;
}
}