物理结构和逻辑结构
什么是栈
栈的基本操作
入栈
/**
*入栈
* @param data
*/
public void push(int data) throws Exception{
// System.out.println("-->"+top);
if(top >=array.length-1 ){
throw new Exception("爆栈");
}
array[++top] = data;
}
出栈
/**
* 出栈
* @return
*/
public int pop() throws Exception{
if(top<0){
throw new Exception("空栈");
}
return array[top--];
}
完整代码:
public class MyStack {
private int[] array;
private int top;
public MyStack(int capacity){
this.array = new int[capacity];
this.top = -1;
}
/**
*入栈
* @param data
*/
public void push(int data) throws Exception{
// System.out.println("-->"+top);
if(top >=array.length-1 ){
throw new Exception("爆栈");
}
array[++top] = data;
}
/**
* 出栈
* @return
*/
public int pop() throws Exception{
if(top<0){
throw new Exception("空栈");
}
return array[top--];
}
public static void main(String[] args) throws Exception {
MyStack ms = new MyStack(5);
ms.push(1);
ms.push(5);
ms.push(9);
ms.push(8);
ms.push(99);
System.out.println(ms.pop());
System.out.println(ms.pop());
System.out.println(ms.pop());
System.out.println(ms.pop());
System.out.println(ms.pop());
System.out.println(ms.pop());
}
}
/*
99
8
9
5
1
Exception in thread "main" java.lang.Exception: 空栈
at MyStack.pop(MyStack.java:28)
at MyStack.main(MyStack.java:44)
*/
什么是队列
队列的基本操作
入队
出队
public class MyCircleQueue {
private int[] array;
private int front;
private int rear;
public MyCircleQueue(int capacity){
this.array = new int[capacity];
}
/**
* 入队
* @param element
* @throws Exception
*/
public void enQueue(int element) throws Exception{
if((rear+1)%array.length == front){
throw new Exception("队列已满!");
}
array[rear] = element;
rear = (rear+1) % array.length;
}
/**
* 出队
* @return
* @throws Exception
*/
public int deQueue() throws Exception{
if (rear == front){
throw new Exception("队列已空");
}
int deQueueElement = array[front];
front = (front+1)%array.length; // front ++ (循环的)
return deQueueElement;
}
public static void main(String[] args) throws Exception {
//队尾指针指向的位置永远空一位
MyCircleQueue mcq = new MyCircleQueue(5);
mcq.enQueue(5);
mcq.enQueue(3);
mcq.enQueue(4);
mcq.enQueue(66);
// mcq.enQueue(2);
System.out.println(mcq.deQueue());
System.out.println(mcq.deQueue());
System.out.println(mcq.deQueue());
System.out.println(mcq.deQueue());
System.out.println(mcq.deQueue());
}
}
/*
5
3
4
66
Exception in thread "main" java.lang.Exception: 队列已空
at MyCircleQueue.deQueue(MyCircleQueue.java:29)
at MyCircleQueue.main(MyCircleQueue.java:46)
*/