赞
踩
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("弹出了元素:"+obj); System.out.println("弹出后个数为:"+stackll.getLength()); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。