- 栈
- 概念
- 栈的使用方法
- MyStack的实现
- 队列
- 概念
- 使用方法
和ArrayList和LinkedList一样,是一种线性表,但是需要遵循特殊的规定——先入后出,后入先出。
数据插入栈的操作叫做压栈,删除叫做出栈
| 方法 | 功能 |
|---|---|
| Stack() | 构造一个空的栈 |
| E push(E e) | 将e入栈,并返回e |
| E pop() | 将栈顶元素出栈并返回 |
| E peek() | 获取栈顶元素 |
| int size() | 获取栈中有效元素个数 |
| boolean empty() | 检测栈是否为空 |
import java.util.Arrays;
public class MyStack {
public int[] elem;
public int usedSize;
public MyStack() {
this.elem = new int[5];
}
public void push(int val){
if(isFUll()){
this.elem = Arrays.copyOf(this.elem,2 * this.elem.length);
}
this.elem[this.usedSize] = val;
this.usedSize++;
}
public boolean isFUll(){
return this.usedSize == this.elem.length;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("the stack is empty");
}
int oldVal = this.elem[usedSize - 1];
this.usedSize--;
return oldVal;
}
public boolean isEmpty(){
return this.usedSize == 0;
}
public int peak(){
if(isEmpty()){
throw new RuntimeException("the stack is empty");
}
return this.elem[usedSize - 1];
}
}
队列
概念
和栈差不多,只不过要求是先入先出,后入后出
使用方法| 方法 | 功能 |
|---|---|
| boolean offer(E e) | 入队列 |
| E poll() | 出队列 |
| peek() | 获取队头元素 |
| int size() | 获取队列中有效元素个数 |
| boolean isEmpty() | 检测队列是否为空 |



