-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingArray.java
More file actions
executable file
·55 lines (40 loc) · 1.12 KB
/
Copy pathStackUsingArray.java
File metadata and controls
executable file
·55 lines (40 loc) · 1.12 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
package com.codeWithArsalon.LinearDS;
import java.util.Arrays;
public class StackUsingArray {
private int [] items = new int[5];
private int [] newItems;
private int count;
public void push (int item){
resizeIfRequired();
items[count++] = item;
}
private void resizeIfRequired() {
if (items.length == count) {
newItems = new int[count * 2];
for (int i = 0; i < count; i++)
newItems[i] = items[i];
items = newItems;
}
}
public int pop (){
if(count == 0)
throw new IllegalStateException();
return items[--count];
}
public int peek(){
if(count == 0)
throw new IllegalStateException();
return items[count - 1];
}
public boolean isEmpty(){
return count == 0;
}
@Override
public String toString(){
var array = Arrays.copyOfRange(items, 0 , count); //copies array contents from 0 to count into separate array
return Arrays.toString(array);
}
public int [] getStack(){
return items;
}
}