一,封装栈结构
栈的结构特点是先进后出,使用数组就可以简单模拟其特点。
/**
* 用数组封装的队列结构
*/
public class MyStack {
int[] data;
int top = 0;
public MyStack(int size){
this.data = new int[size];
}
public void push(int val) throws Exception {//入栈
if(top == this.data.length){
throw new Exception("满了");
}
data[top] = val;
top ++ ;
}
public int pop() throws Exception {//出栈
if(top == 0 ){
throw new Exception("为空");
}
top--;
return this.data[top];
}
public boolean isEmpty(){//判断当前栈是否为空
if(this.top == 0)
return true;
else
return false;
}
}
public class Main {
public static void main(String[] args) throws Exception {
MyStack stack = new MyStack(5);//创建一个栈结构
stack.push(1);//压入数据
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
//stack.push(6);//测试是否越界
int a = stack.pop();//弹出数据
int b = stack.pop();
int c = stack.pop();
int d = stack.pop();
int e = stack.pop();
System.out.println(a+" "+b+" "+c+ " "+d+" "+e);
}
}
一,封装队列结构
队列的结构特点是先进者先出,利用链表的结构就可以简单模拟其特点。
public class Node {
public int val;
public Node next;
public Node(int val){
this.val = val;
}
}
/**
* 用链表封装的队列结构
*/
public class MyQueue {
Node head = null;
Node tail = null;
int maxSize;
int size;
public MyQueue(int maxSize){
this.maxSize = maxSize;
this.size = 0;
}
public void push(int val) throws Exception {//入队列
if(size >= maxSize){
throw new Exception("满了");
}
Node node = new Node(val);
if(size==0){
this.head = node;
this.tail = node;
}else {
tail.next = node;
tail = node;
}
size ++;
}
public int pop() throws Exception {//出队列
if(size == 0){
throw new Exception("为空");
}
int result = head.val;
head = head.next;
size -- ;
return result;
}
public class Main {
public static void main(String[] args) throws Exception {
MyQueue queue = new MyQueue(5);//创建队列
queue.push(1);//放入数据
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
//queue.push(6);//测试是否越界
int a = queue.pop();//取出数据
int b = queue.pop();
int c = queue.pop();
int d = queue.pop();
int e = queue.pop();
System.out.println(a+" "+b+" "+c+ " "+d+" "+e);
}
}