1. 栈 (stack)
栈满足“先进后出”,换句话说就是“后进先出”。
图片来自网络,侵删用数组模拟一个栈实现如下:
package com.stackAndQueue;
public class myStack {
private int[] elem;
public myStack(){
int[] elem = new int[0];
}
/**
* 向栈顶压入元素。和可变数组中添加元素的方法完全一样
* @param n 被压入的元素
* */
public void push(int n){
int[] newArr = new int[elem.length + 1];
newArr[elem.length] = n;
for (int i = 0; i < elem.length; i++){
newArr[i] = elem[i];
}
elem = newArr;
}
/**
* 取出栈顶元素
* @return 被取出栈顶元素
* */
public int pop(){
if (this.isEmpty()){
throw new RuntimeException("The stack is empty.");
}
int ele = elem[elem.length - 1];
int[] newArr = new int[elem.length - 1];
for (int i = 0; i < newArr.length; i++){
newArr[i] = elem[i];
}
elem = newArr;
return ele;
}
/**
* 查看栈顶元素
* @return 栈顶元素
* */
public int peek(){
if(this.isEmpty()){
throw new RuntimeException("The stack is empty!");
}
return elem[elem.length - 1];
}
/**
* 检查列表是否为空?
* */
public boolean isEmpty(){
return (elem.length == 0);
}
}
2. 队列 (Queue)
队列则是“先进先出”。
图片来自网络,侵删用数组模拟一个队列如下:
package com.stackAndQueue;
public class MyQueue {
private int[] queue;
public MyQueue(){
int[] queue = new int[0];
}
/**
* 入队
* @param n 入队的元素
* */
public void offer(int n){
int[] tmp = new int[queue.length + 1];
tmp[queue.length] = n;
for(int i = 0; i < queue.length; ++i){
tmp[i] = queue[i];
}
queue = tmp;
}
/**
* 出队
* @return 要出队的元素
* */
public int poll(){
if (this.isEmpty())
throw new RuntimeException("The queue is empty!");
int res = queue[0];
int[] tmp = new int[queue.length - 1];
for (int i = 0; i < tmp.length; ++i){
tmp[i] = queue[i + 1];
}
queue = tmp;
return res;
}
/**
* 判断队列是否为空
* @return true or false
* */
public boolean isEmpty(){
return queue.length == 0;
}
}
网友评论