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

java数据结构——链表实现栈,第1张

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

package fwb.COllection;

/**
 * @author :yixing
 * @Have a nice day!
 * @date : 2022/5/6
 * @time :  16:39
 */

//栈的链表实现
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("d出了元素:"+obj);
        System.out.println("d出后个数为:"+stackll.getLength());

    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/889985.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-14
下一篇2022-05-14

发表评论

登录后才能评论

评论列表(0条)

    保存