5 栈的实现

1 栈的描述

栈是一个先入后出(FILO-First In Last Out)的有序列表。
栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除

2 出栈(pop)和入栈(push)的概念

在这里插入图片描述

在这里插入图片描述

3 栈的实现

package stack;

public class LinkStact<T> {
    private Node<T> top;

    /**
     * 返回节点是否为空
     * @return
     */
    public boolean isEmpty(){
        return top == null;
    }

    /**
     * 进栈,创建一个节点,把该节点放到一个个位置
     * @param value
     */
    public void push(T value){
        Node node = new Node(value, top);
        top = node;
    }

    /**
     * 出
     */
    public T pop(){
        if (isEmpty())
        {
            throw new RuntimeException("栈已经为空!");
        }
        Node<T> temp = top;
        top = top.getNext();
        return  temp.getData();
    }

    public void show(){
        if (isEmpty())
        {
            System.out.println("栈已经为空!");
            return;
        }
        Node node = top;
        System.out.println("栈内的数据为: ");
        while (node != null){
            System.out.print(node.getData() + " ");
            node = node.getNext();
        }
        System.out.println();
    }

    /**
     * 测试栈
     * @param args
     */
    public static void main(String[] args) {
        LinkStact<Integer> stact = new LinkStact();
        stact.push(1);
        // stact.push(2);
        // stact.push(3);
        // stact.push(4);
        // stact.push(5);

        //stact.show();
        System.out.println(stact.pop());
        stact.push(2);
        stact.push(3);
        stact.show();
        System.out.println(stact.pop());
        System.out.println(stact.pop());
        stact.show();

    }
}

/**
 * 节点class
 */
class Node<T>{
    private T data;
    private Node<T> next;

    public Node() {
    }

    public Node(T data, Node next) {
        this.data = data;
        this.next = next;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

4 java集合中的栈

java.util.Stack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值