目录
1.栈
2.队列
3.测试
项目结构:
1.栈
Stack.java
/*
栈:用数组实现
*/
public class Stack {
private int[] array;
private int top;//栈顶
public Stack(){
array = new int[10];
}
public Stack(int capacity){//栈的深度
array = new int[capacity];
}
//获取栈的深度
public int getStackLength(){
return array.length;
}
/**
* 压入栈中
* @param element 放入的元素
*/
public void push(int element){
//判断是否栈满
if(top >= array.length){
//对栈进行扩容
expandCapacity(top);
}
array[top] = element;
top++;//栈顶加1
}
//弹出栈中的数据
public int pop(){
return array[--top];
}
public void expandCapacity(int top){
int[] newArray = new int[array.length * 2];
if(newArray.length > 100){
throw new IllegalArgumentException("不准栈的深度超过100");
}
if(top > 0){
System.arraycopy(array,0,newArray,0,top);
}
array = newArray;
}
@Override
public String toString() {
String str = "[";
//只遍历数组当中的元素个数
for(int i = 0;i < top;i++){
str += array[i];
//当不是最后1个元素,需要加逗号
if(i != top - 1){
str += ",";
}
}
//最后加一个"]"结尾
str += "]";
return str;
}
}
2.队列
Queue.java
/*
队列:用数组实现
*/
import java.util.NoSuchElementException;
public class Queue {
private int font;//队头
private int rear;//队尾
private int[] array;
public Queue(){
array = new int[10];
}
public Queue(int capacity){
array = new int[capacity];
}
//获取队列长度
public int getQueueLength(){
return array.length;
}
//入队
public void enQueue(int element){
//判断队列是否队满
if((rear + 1) % array.length == font){
expandCapacity();
}
array[rear] = element;//在队尾加上数据
rear = (rear + 1)%array.length;//添加完数据,队尾往后移
}
//出队
public int outQueue(){
//判断队列是否为空
if(font == rear){
throw new NoSuchElementException("队列为空!无法获取数据!");
}
int outElement = array[font];
font = (font + 1)%array.length;
return outElement;
}
public void expandCapacity(){
int[] newArray = new int[array.length * 2];
if(newArray.length > 100){
throw new IllegalArgumentException("不准栈的深度超过100");
}
//将原数组复制到新数组里
for(int i = 0,n = 0;i < array.length;i++){//队尾可能在数组的中间
if(i == rear){//因为队尾要留一空
continue;
}
newArray[n++] = array[i];
}
array = newArray;
}
@Override
public String toString() {
String str = "[";
//只遍历数组当中的元素个数
for(int i = font;i != rear;i = (i + 1)%array.length){
str += array[i];
//当不是最后1个元素,需要加逗号
if(i != rear - 1){
str += ",";
}
}
//最后加一个"]"结尾
str += "]";
return str;
}
}
3.测试
TestArray.java
public class TestArray {
public static void main(String[] args) {
Queue queue = new Queue(3);
queue.enQueue(1);
queue.enQueue(2);
queue.enQueue(3);
queue.enQueue(4);
queue.enQueue(5);
System.out.println(queue);
System.out.println("出队:");
queue.outQueue();
queue.outQueue();
queue.outQueue();
queue.outQueue();
queue.outQueue();
System.out.println(queue);
}
}
?完
|