-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
45 lines (38 loc) · 1.07 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
/**
* Created by root on 11/18/16.
*/
public class Stack {
private int top;
private String[] data;
public Stack(){
data = new String[100];
top = -1;
}
public void push(String element) {
if (top == data.length){
throw new java.util.NoSuchElementException("Cannot add element. Stack overflow.");
}
data[++top] = element;
}
public String pop(){
if (top == -1){
throw new java.util.NoSuchElementException("Stack is empty (from pop)");
}
return data[top--];
}
public String peek(int index){
if (index > data.length || index > top){
throw new java.util.NoSuchElementException("No element found at that index");
}
return data[top - index];
}
public void print(){
if (top == -1){
throw new java.util.NoSuchElementException("Stack is empty (from printing)");
}
for (int i = 0; i <= top; i++){
System.out.print(data[i] + " ");
}
System.out.println("\n");
}
}