Java数据结构—栈

什么是栈

栈是限定仅在表尾进行插入或删除操作的线性表

栈的特点

  1. 栈是一种操作受限的线性表
  2. 修改是按先进后出的原则

栈在Java中的使用

  1. 基本数据类型、局部变量存放在栈中
  2. 对象的引用变量存放在栈中
  3. 数据一旦执行完毕,栈内存就会释放
  4. 栈内存里的数据,没有初始化,需要手动设置

栈的基本操作

说明:

  1. base表示栈底,top表示栈顶
  2. top = base可作为栈空的标记
  3. 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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值