前期讨论了用链表去实现堆栈和队列,这次使用数组来实现。主要部分还是一样:堆栈对一端ip操作,队列对两端ipHead和ipTail操作。
首先看看堆栈,实现代码如下:
public class ArryStack {
private int ip = 0;
private int [] data = new int [10];
public void push(int idata){
int ipp;
ipp = ip;
data[ip] = idata;
ip++;
System.out.println("push data: "+ data[ipp]);
}
public int pop(){
int ipp;
ipp = ip;
System.out.println("pop data: "+ data[--ipp]);
ip--;
return data[ip];
}
public void displayStackElement(){
int i;
if(ip < 0){
System.out.println("非法操作");
}
else{
for(i = 0; i < ip ; i++){
System.out.println("stack element:"+data[i]);
}
}
}
public static void main(String args []){
ArryStack stack = new ArryStack();
stack.push(1);
stack.push(2);
stack.displayStackElement();
stack.pop();
stack.displayStackElement();
stack.pop();
// stack.pop();
}
}
运行结果:
push data: 1
push data: 2
stack element:1
stack element:2
pop data: 2
stack element:1
pop data: 1
队列实现如下:
public class ArryQueue{
private int ipHead=10;
private int ipTail=10;
int [] data = new int [11];
public void insert(int idata){
data[ipTail] = idata;
ipTail--;
}
public int delete(){
ipHead--;
return data[ipHead];
}
public void dispalyQueue(){
int i;
if(ipTail > ipHead){
System.out.println("非法操作");
}
else{
for(i = ipTail ; i < ipHead ; i++){
System.out.println("queue elemnet: " + data[i+1]);
}
}
}
public static void main(String args[]){
ArryQueue queue = new ArryQueue();
System.out.println("insert");
queue.insert(1);
//queue.dispalyQueue();
queue.insert(2);
queue.insert(3);
queue.dispalyQueue();
System.out.println("delete");
queue.delete();
queue.dispalyQueue();
System.out.println("delete");
queue.delete();
queue.dispalyQueue();
}
}
运行结果如下:
insert
queue elemnet: 3
queue elemnet: 2
queue elemnet: 1
delete
queue elemnet: 3
queue elemnet: 2
delete
queue elemnet: 3