栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java数据结构——链表实现栈

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java数据结构——链表实现栈

java数据结构——链表实现栈

package fwb.COllection;



//栈的链表实现
class LLNode{
    private Object data; //存放数据
    private LLNode next; //指向下一个节点
    public LLNode(){}
    public LLNode(Object data){
        this.data =data;
    }
    public Object getData(){
        return data;
    }
    public void setData(Object data){
        this.data = data;
    }
    public LLNode getNext(){
        return next;
    }
    public void setNext(LLNode next){
        this.next = next;
    }

}
public class StackLL {
    LLNode headNode = null;
    public StackLL(){
        headNode = new LLNode(null);
    }
    //入栈
    public void push(Object data){
        if(headNode.getData() == null){
            headNode.setData(data);
        }
        else if(headNode == null){
            headNode = new LLNode(data);
        }
        else{

            LLNode newNode = new LLNode(data);
            newNode.setNext(headNode);  //头插
            headNode = newNode;

        }
    }
    public boolean isEmpty(){
        return headNode == null;
    }
    //出栈
    public Object pop(){
        Object data = null;
        if(isEmpty()){
            System.out.println("栈为空");
            return 0;
        }
        data = headNode.getData();
        headNode = headNode.getNext();
        return data;
    }
    //统计栈里元素的个数并显示
    public int getLength(){
        int count = 0;
        LLNode cur = headNode;
        if(isEmpty()||cur.getData()==null){
            count = 0;
        }
        else{
            while(cur != null){
                //System.out.println(count+"->"+cur.getData());
                count++;
                cur = cur.getNext();

            }
        }
        return count;
    }

    public static void main(String[] args) {
        StackLL stackll = new StackLL();
        stackll.push(1);
        stackll.push(2);
        stackll.push(3);
        System.out.println("个数为:"+stackll.getLength());

        Object obj = stackll.pop();
        System.out.println("弹出了元素:"+obj);
        System.out.println("弹出后个数为:"+stackll.getLength());

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/872514.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号