数据结构之链式堆栈java实现

数据结构里经常把堆栈和队列放一起,个人感觉堆栈和队列的实现方式难度差不多,仅当动手学习,参靠参考。

public class stackLinkList {
    public static StackNode[] arr;
    public static void main(String[] args) {
        StackNode no = new StackNode("a");
        StackNode no0 = new StackNode("b");
        StackNode no1 = new StackNode("c");
        arr = new StackNode[]{no,no0,no1};//用一个数组储存便于遍历结点
        initStack(no);//初始化堆栈
        push(no0);//进栈
        push(no1);
        showStack();//遍历堆栈
        System.out.println("---------------------------");
        pop();//出栈
        showStack();//遍历堆栈
    }
    public static void pop(){
        for (int i=0; i<arr.length; i++){
            if (arr[i].isHead() == true){
                arr[i].getNext().setHead(true);
                arr[i]=null;
            }
        }
    }
    public static void initStack(StackNode stack){
        stack.setHead(true);
        stack.setNext(null);
    }
    public static void showStack(){
        for (int i=0; i<arr.length; i++){
            if(arr[i] != null){
                arr[i].showStack();
            } else {
                System.out.println(arr[i]);
            }
        }
    }
    public static StackNode top(){
        StackNode nn = new StackNode();
        for (int i=0; i<arr.length; i++){
            if (arr[i].isHead() == true){
                nn=arr[i];
            }
        }
        return nn;
    }
    public static void push(StackNode newStack){
        newStack.setNext(top());
        top().setHead(false);
        newStack.setHead(true);
    }
}
class StackNode<T>{
    private T data;
    private StackNode next;
    private boolean isHead = false;

    public StackNode() {
    }

    public StackNode(T data) {
        this.data = data;
    }

    public T getData() {
        return data;
    }

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

    public StackNode getNext() {
        return next;
    }

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

    public boolean isHead() {
        return isHead;
    }

    public void setHead(boolean head) {
        isHead = head;
    }

    public void showStack() {
        if(this.next == null){
            System.out.println("stackNode{" +
                    "data=" + data +
                    ", next=" + next +
                    ",isHead=" + isHead +
                    '}');
        } else {
            System.out.println("stackNode{" +
                    "data=" + data +
                    ", next=" + (next.getData() == null ? null : next.getData()) +
                    ",isHead=" + isHead +
                    '}');
        }
    }
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值