-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreeStack.java
More file actions
83 lines (73 loc) · 1.77 KB
/
ThreeStack.java
File metadata and controls
83 lines (73 loc) · 1.77 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Describe how you could use a single array to implement three stacks.
package edu.java.chap3;
public class ThreeStack {
public static void change(int[] arr){
arr[0]=1;
}
public static void method1(){
int[] arr = new int[20];
//int[] ar1 = Arrays.copyOfRange(arr, 0, arr.length/3);
//System.out.println(ar1.length);
//int[] ar2 = Arrays.copyOfRange(arr,arr.length/3,arr.length/3+arr.length/3);
//int[] ar3 = Arrays.copyOfRange(arr,arr.length/3+arr.length/3,arr.length);
//System.out.println(ar3.length);
stack st1 = new stack(arr,0,arr.length/3-1);
stack st2 = new stack(arr,arr.length/3,2*arr.length/3-1);
stack st3 = new stack(arr,2*arr.length/3,arr.length);
st1.push(1);
st2.push(3);
st3.push(4);
System.out.println(st1.pop());
System.out.println(st1.pop());
for(int i = 0; i<arr.length;i++){
System.out.print(arr[i]);
}
}
public static void main(String[] args) {
method1();
/*System.out.println(arr[0]);
change(arr);
System.out.println(arr[0]);
stack st = new stack(arr);
System.out.println(st.arr[0]);
st.set();
System.out.println(st.arr[0]);
System.out.println(arr[0]);
*/
}
}
class stack{
public int[] arr;
public int pos;
public int start;
public int end;
public stack(int[] arr,int start,int end){
this.arr = arr;
this.pos = start;
this.start = start;
this.end = end;
}
//test the reference of arr is passed into the class
public void set(){
this.arr[0] = 2;
}
public void push(int x){
if(pos<=end){
this.arr[this.pos] = x;
this.pos++;
}
else{
System.out.println("this stack is full, try others");
}
}
public int pop(){
if(pos>start){
int result = this.arr[this.pos-1];
this.pos--;
return result;
} else {
System.out.println("this stack is empty");
return 0;
}
}
}