-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
57 lines (48 loc) · 1.24 KB
/
Stack.java
File metadata and controls
57 lines (48 loc) · 1.24 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
package queue;
public class Stack {
private int[] items = new int[100];
private int top = -1; //index to keep track of the topmost element
public boolean isEmpty() {
return top < 0;
}
public void push(int item) {
if (top == items.length-1)
throw new RuntimeException("Stack is full");
items[++top] = item;
}
/**
* Returns the topmost item and removes it
* @return
*/
public int pop() {
if (isEmpty())
throw new RuntimeException("Stack is empty");
return items[top--];
}
/**
* Returns the topmost item without removing it
* Peek and Pop methods should ideally be invoked after checking that the stack is not empty
* either in a 'if' condition or a 'while' loop
* @return
*/
public int peek() {
if (isEmpty())
throw new RuntimeException("Stack is empty");
return items[top];
}
public static void main(String[] args) {
Stack stack = new Stack();
System.out.println(stack.isEmpty());
stack.push(5);
stack.push(4);
stack.push(6);
stack.push(10);
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}