1.什么是栈?
2.定义
栈(stack)是一个有序线性表,只能在一端执行插入和删除操作,最后插入的元素将被第一个删除(后进先出)
3.栈的操作
3.1主要操作
push(int data):将data(数据)插入栈
int pop():删除并返回最后一个插入栈的元素
3.2辅助操作
int top():返回最后一个插入栈的元素,但不删除(top也可能是属性)
int size():返回存储在栈中元素的个数
boolean isEmpty():判空
boolean isFull():判断栈中是否存满元素
4.异常
对一个满栈执行push操作会抛出溢出(overflow)
对一个空栈执行pop操作会抛出下溢(underflow)
5.栈的实现
当栈空时top = -1
5.1基于简单数组实现
public class Stack{
private int top; //指针
private int capacity; //栈空间大小
private int[] ary; // 数组模拟的栈
//Getters and Setters
public Stack(int capacity){
this.capacity = capacity;
ary = new int[capacity];
top = -1;
}
public Stack() {
this(25);
}
//判空
public boolean isEmpty(){
return size() == 0;
}
//判满
public boolean isFull(){
return size() == capacity;
}
//返回栈中元素个数
public int size(){
return top + 1;
}
//入栈
public void push(int data){
if(isFull()){
throw new RuntimeException("Stack overflow");
}
ary[++top] = data;
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack underflow");
}
return ary[top--];
}
//清空栈
public void clear(){
top = -1;
}
}
5.2基于动态数组实现
public class Stack{
private int top; //指针
private int capacity; //栈空间大小
private int[] ary; // 数组模拟的栈
//Getters and Setters
public Stack(){
this.capacity = 1;
ary = new int[capacity];
top = -1;
}
//判空
public boolean isEmpty(){
return size() == 0;
}
//判满
public boolean isFull(){
return size() == capacity;
}
//返回栈中元素个数
public int size(){
return top + 1;
}
private void ensureCapacity(){
int[] newary = new int[capacity * 2];
System.arraycopy(ary, 0, newary, 0, capacity);
capacity *= 2;
ary = newary;
}
//入栈
public void push(int data){
if(isFull()){
ensureCapacity();
}
ary[++top] = data;
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack underflow");
}
return ary[top--];
}
//清空栈
public void clear(){
top = -1;
}
}
5.3基于链表实现
public class Stack{
private static class Node{
int data;
Node next;
public int getData(){
return data;
}
public void setData(int data){
this.data = data;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
public Node(int data){
this.data = data;
}
public Node(){
}
}
private Node head; //表头节点
public Stack(){
head = new Node();
}
//判空
public boolean isEmpty(){
return head.getNext() == null;
}
//top指针,指向栈顶元素
public int top(){
return head.getNext().getData();
}
//清空
public void clear(){
head.setNext(null);
}
//入栈
public void push(int data){
Node node = new Node(data);
if(head.getNext() == null){
head.setNext(node);
}else{
node.setNext(head.getNext());
head.setNext(node);
}
}
//出栈
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack underflow");
}
Node temp = head.getNext();
head.setNext(temp.getNext());
return temp.getData();
}
}