Stack 栈 java实现

4 篇文章 0 订阅
1 篇文章 0 订阅
package dataStructure.Stack;

public class Stack<T> {
	private static class stackNode<T>{
		//栈结点元素
		private T data;
		private stackNode<T> next;

		stackNode(T data){
			this.data = data;
		}
	}

	private stackNode<T> top;
	private stackNode<T> bottom;
	private int height;

	/**
	 * 初始化栈
	 */
	public Stack(){
		top = null;
		bottom = null;
		height = 0;
	}

	/**
	 * 往栈顶添加元素(入栈)
	 * @param node
	 */
	public void push(stackNode<T> node){
		if (this.isEmpty()){
			top = node;
			bottom = node;
			height ++;
			return;
		}
		node.next = top;
		top = node;
		height++;
		return;
	}

	/**
	 * 将栈顶元素出栈
	 * @return
	 */
	public stackNode<T> pop(){
		stackNode<T> temp = top;
		if (!this.isEmpty()){
			top = top.next;
			height--;
			return temp;
		}
		return null;
	}

	/**
	 * 显示当前栈中的元素
	 */
	public void display(){
		stackNode<T> temp = top;
		while (temp != null){
			System.out.print(temp.data + "\t");
			temp = temp.next;
		}
		System.out.println();
	}

	/**
	 * 取出栈顶元素,不出栈
	 * @return
	 */
	public stackNode<T> poll(){
		stackNode<T> temp = top;
		temp.next = null;
		return temp;
	}

	/**
	 * 判断栈是否为空
	 * @return
	 */
	public boolean isEmpty(){
		return height == 0;
	}

	/**
	 * 清空栈
	 */
	public void emptyStack(){
		top = bottom = null;
		height = 0;
	}

	public static void main(String[] args){
		Stack<Integer> s = new Stack<>();
		s.push(new stackNode<>(1));
		s.push(new stackNode<>(2));
		s.push(new stackNode<>(3));
		s.push(new stackNode<>(4));
		s.push(new stackNode<>(5));
		s.push(new stackNode<>(4));
		s.push(new stackNode<>(3));
		s.push(new stackNode<>(2));
		s.push(new stackNode<>(1));
		s.display();
		s.pop();
		s.display();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值