1、用静态数组实现队列的基本操作
思路 :创建3个变量,start,end,size; size用来查看数组中数据的数量,从而实现添加和删除的长度控制。当添加数据时,如果end=size-1;说明end已经指向最后一位。所以:end = end==size-1 ? 0 : end++; 当删除数据时,若size>0.删除start指向的数据,start = start == arr.length-1?0:start++;
package algorithm;
import java.util.EmptyStackException;
/**
* 用静态数组实现队列的基本操作
* 用3个元素记录
* 实现数组的循环利用
* @author hasee
*
*/
public class Queue1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue q = new Queue(3);
q.offer(1);
System.out.println(q.peek());
}
static class Queue {
int [] arr ;
int start,end,size;
public Queue(int i) {
if(i<0)
throw new IllegalArgumentException("the length of Quene is smaller than 0");
arr = new int[i];
start = 0;
end = 0;
size = 0;
}
//入队
public void offer(int i) {
if(size == arr.length) {
throw new IndexOutOfBoundsException("the queue id full");
}
arr[end] = i;
end = end==arr.length-1?0:end++;
size++;
}
//出队
public int pop() {
if(size==0) {
throw new EmptyStackException();
}
int temp = start;
start = start == arr.length-1?0:start++;
size--;
return arr[temp];
}
//返回第一个值
public int peek() {
if(size==0) {
throw new EmptyStackException();
}
return arr[start];
}
}
}
2.用栈实现队列
思路:创建两个栈,一个data 一个help。当需要输入数据的时候,往data栈里添加。输出数据的时候,查看data.size()>0.将data栈中的数据都放到help栈中,输出help栈顶,再将help栈的数据都放到data中。
package algorithm;
import java.util.Stack;
/**
* 用栈实现队列
* @author hasee
*
*/
public class Queue2 {
public static void main(String[] args) {
Queue q = new Queue();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
System.out.println(q.peek());
System.out.println(q.peek());
}
static class Queue {
private Stack<Integer> data = new Stack<Integer>();
private Stack<Integer> help = new Stack<Integer>();
//加入新元素
public void add(int i) {
// TODO Auto-generated method stub
data.push(i);
}
//出队列
public int remove() {
if(data.size()==0)
throw new NullPointerException("the queue is null");
int size1 = data.size();
for(int i = 0;i < size1;i++) {
help.push(data.pop());
}
int result = help.pop();
int size2 = help.size();
for(int j = 0;j < size2;j++)
data.push(help.pop());
return result;
}
//返回队列第一个元素 但不删除
public int peek() {
if(data.size()==0)
throw new NullPointerException("the queue is null");
while(data.size()>0) {
help.push(data.pop());
}
int result = help.peek();
while(help.size()>0){
data.push(help.pop());
}
return result;
}
}
}