import java.util.*; public class NonZeroNumStack{ private int[] data; private in
ID: 3711667 • Letter: I
Question
import java.util.*;
public class NonZeroNumStack{
private int[] data;
private int total;
public NonZeroNumStack(){
data=new int[10];
total=0;
}
public int pop(){
if(isEmpty())
return 0;
else{
return data[--total];
}
}
public int top(){
if(isEmpty())
return 0;
else
return data[total-1];
}
public void push(int num){
if(num==0) return;
if(data.length==total){
int[] tmp=new int[total*2];
for(int i=0; i<total; i++)
tmp[i]=data[i];
data=tmp;
}
data[total++]=num;
}
public void push(int[] arr){
for(int i=0; i<arr.length; i++)
push(arr[i]);
}
public int size(){
return total;
}
public boolean isEmpty(){
return total==0;
}
public boolean isFull(){
return false;
}
}
Explanation / Answer
Below are the 2 methods implemented:
public void mergePair(NonZeroNumStack stack) {
if(stack.total%2==0) {
int newtotal = stack.total/2;
int[] newdata = new int[newtotal];
for(int i = 0;i<newtotal;i++) {
newdata[i] = stack.data[i*2] + stack.data[(i*2)+1];
}
stack.total = 0;
stack.data = new int[10];
stack.push(newdata);
}
else {
int newtotal = (stack.total/2)+1;
int[] newdata = new int[newtotal];
for(int i = 0;i<newtotal-1;i++) {
newdata[i] = stack.data[i*2] + stack.data[(i*2)+1];
}
newdata[newtotal-1] = stack.data[total-1];
stack.total = 0;
stack.data = new int[10];
stack.push(newdata);
}
}
public int removeLastMin(NonZeroNumStack stack) {
int min = stack.data[0];
int minIndex = 0;
for(int i = 1;i<stack.total;i++) {
if(stack.data[i]<=min) {
min = stack.data[i];
minIndex = i;
}
}
for(int j = minIndex;j < stack.total-1;j++) {
stack.data[j] = stack.data[j+1];
}
stack.data[total--] = 0;
return min;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.