基本数据结构-栈

本文介绍了一种使用链表和数组实现栈的数据结构方法。通过具体的Java代码示例展示了如何进行元素的压入与弹出操作,并提供了打印栈内元素的方法。

基于链表

package info.zh93.DS;

/**
 * Created by zhanghao on 2016.09.23.
 */
public class StackClass {
    public class Node{
        public String data;
        public Node before;

        public Node(String data) {
            this.data = data;
        }

        public Node(String data, Node before) {
            this.data = data;
            this.before = before;
        }
    }

    //根节点
    private Node last = null;

    //压入栈中
    public void push(String data){
        if (last == null){
            last = new Node(data, null);
            return;
        }
        Node inner = new Node(data, last);

        last = inner;
    }

    //弹出
    public String pop() throws Exception {
        if (last != null){
            Node node = last;
            last = last.before;
            return node.data;
        }
        return null;
    }
    public void printStack(){
        Node node = last;
        while (node != null){
            System.out.println(node.data);
            node = node.before;
        }
    }

    public static void main(String[] strs) throws Exception {
        StackClass sc = new StackClass();
        for (int i = 0; i < 10; i++){
            sc.push(i + "");
            System.out.println("pop: " + sc.pop());
        }
        sc.printStack();
    }
}

基于数组

转载于:https://www.cnblogs.com/hgod/articles/5902101.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值