定义
一种线性的存储结构,实现先进后出的原则,用链表实现的时候只能从头节点开始才能实现完整的铺上,pop,peap的完整操作,不同于数组的实现,链表不需要判断栈不否满了,只需要判断是否为空。
入栈:在头指针后面插入数据;
出栈:把头指针后一位的数据输出;
链表的定义
package com.jiedada.jiegou; public class Node1 { private Object data; private Node1 next; public Node1() { this.data=null; this.next=null; } public Node1(Object data) { this.data=data; this.next=null; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Node1 getNext() { return next; } public void setNext(Node1 next) { this.next = next; } }
链表的实现方法
package com.jiedada.jiegou; public class Link { Node1 head=null; public Link() { head=new Node1(); } //入栈 public void push(Object obj) { Node1 node=new Node1(obj); //把node和head连接 node.setNext(head.getNext()); //把node变成head的位置 head.setNext(node); } //是否为空 public boolean isEempty() { return (head.getNext()==null); } //出栈 public Object pop() { Object item=null; if(isEempty()) { System.out.println("该栈为空"); //return item; } item=head.getNext().getData(); head.setNext(head.getNext().getNext()); return item; } //堆栈大小 public int size() { int len = 0; Node1 pNode = head; while (pNode.getNext() != null) { len++; pNode = pNode.getNext(); } return len; } //读取堆栈元素 public Object peak() { Object item=null; if(isEempty()) { System.out.println("该栈为空"); return item; } item=head.getNext().getData(); return item; } public static void main(String[] args) { // TODO Auto-generated method stub Link link=new Link(); link.push("第一个"); link.push("第二个"); link.push("第三个"); link.push("第四个"); System.out.println(link.isEempty()); System.out.println(link.size()); System.out.println(link.pop()); System.out.println(link.peak()); System.out.println(link.size()); } }
代码连接为:https://www.cnblogs.com/neuhao/p/6497000.html