什么是栈
栈是限定仅在表尾进行插入或删除操作的线性表
栈的特点
- 栈是一种操作受限的线性表
- 修改是按先进后出的原则
栈在Java中的使用
- 基本数据类型、局部变量存放在栈中
- 对象的引用变量存放在栈中
- 数据一旦执行完毕,栈内存就会释放
- 栈内存里的数据,没有初始化,需要手动设置
栈的基本操作
说明:
- base表示栈底,top表示栈顶
- top = base可作为栈空的标记
- base的值为null,则栈结构不存在
class LinkStack<T> {
private int size;
private Node base = null;
private Node top = null;
private class Node{
private T t = null;
private Node next = null;
}
public LinkStack() {
this.size = 0;
this.base = null;
this.top = this.base;
this.base.next = null;
this.base.t = null;
}
public boolean stackEmpty() {
return this.size == 0;
}
public int stackSize() {
return this.size;
}
public void push(T obj) {
Node newNode = new Node();
newNode.t = obj;
newNode.next = top;
top = newNode;
size++;
}
public T pop() {
if(this.top == this.base) return null;
Node popNode = this.top;
this.top = popNode.next;
popNode.next = null;
size--;
return popNode.t;
}
public void show() {
Node showNode = this.base;
for(int i = 0 ; i < this.size ; i++) {
System.out.println(showNode.t.toString());
}
}
}
class Book {
private String title;
private double price;
public Book(String title,double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "title: " +title+" price: " +price;
}
}