栈
栈作为一种数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)
栈的入栈和出栈过程
图片(注:百度搜索而来的图片)链接: link.
java代码实现
// An highlighted block
import java.util.Random;
public class Stack {
private int[] arr;
private int size;
private int capacity;
public Stack() {
this.arr = new int[10];
this.size = 0;
this.capacity = 10;
}
public static void main(String[] args) {
Stack stack = new Stack();
Random random = new Random();
for (int i = 0; i < 20; i++) {
stack.push(random.nextInt(50));
System.out.println(stack.toString());
//System.out.printf("stack's size is %d, this capacity is %d\n",stack.getSize(),stack.capacity);
}
for (int i = 0; i < 18; i++) {
try {
int pop = stack.pop();
System.out.println(pop);
System.out.println(stack.toString());
//System.out.printf("stack's size is %d, this capacity is %d\n",stack.getSize(),stack.capacity);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(stack.toString());
}
/**
* 进栈
*
* @param e
*/
public void push(int e) {
_add(e);
}
private void _add(int e) {
if (this.size >= this.capacity) {
this.capacity = this.capacity * 2;
int[] newarr = new int[this.capacity];
for (int i = 0; i < this.size; i++) {
newarr[i] = this.arr[i];
}
this.arr = newarr;
}
this.arr[this.size] = e;
this.size++;
}
/**
* 出栈
*
* @return
* @throws Exception
*/
public int pop() throws Exception {
if (this.size < 1) throw new Exception("The stack was empty");
int popElement = this.arr[this.size - 1];
this.size--;
if (this.size <= this.capacity / 4) {
this.capacity = this.capacity / 2;
int[] newarr = new int[this.capacity];
for (int i = 0; i < this.size; i++) {
newarr[i] = this.arr[i];
}
this.arr = newarr;
}
return popElement;
}
/**
* 栈顶元素
*
* @return
* @throws Exception
*/
public int peek() throws Exception {
if (this.size < 1) throw new Exception("The stack was empty");
int peekElement = this.arr[this.size - 1];
return peekElement;
}
public int getSize() {
return this.size;
}
public boolean isEmpty() {
return this.size <= 0;
}
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < this.size; i++) {
stringBuffer.append(arr[i] + " - ");
}
return stringBuffer.toString();
}
}