java 简单链表

来源:互联网 发布:python 制作辅助 编辑:程序博客网 时间:2024/06/08 00:38

java中没有指针的概念,但是有对象的引用,java中链表的实现就是通过对象的引用实现的。下面是一个链表的简单实现

class Link {class Element {public Object value = null;public Element nextNode = null;}private Element header = null;public void add(Object node) {if (header == null) {header = new Element();header.value = null;header.nextNode = null;}Element element = new Element();element.value = node;element.nextNode = header.nextNode;header.nextNode = element;}public boolean remove(Object obj) {if (header == null) {return false;}Element pre = header;Element ele = header.nextNode;while(ele != null) {if (ele.value == obj) {pre.nextNode = ele.nextNode;return true;}pre = ele;ele = ele.nextNode;}return false;}public void clear() {header = null;}public boolean contains(Object obj) {if (header == null) {return false;}Element elm = header.nextNode;while(elm != null) {if (elm.value == obj) {return true;}elm = elm.nextNode;}return false;}public Element getElement(int index) {if (header == null) {return null;}if (index > (this.Size()-1) || index < 0) {return null;}int i = 0;Element ele = header.nextNode;while(ele != null) {if (i == index) {return ele;}i++;ele = ele.nextNode;}return null;}public int Size() {if (header == null) {return 0;}int size = 0;Element ele = header.nextNode;while(ele != null) {size++;ele = ele.nextNode;}return size;}public boolean checkLoop(){if (header==null) {return false;}int size = this.Size();if (size == 0) {return false; }Set<Element> set = new HashSet<Element>();for (int i = 0; i < size ;i ++) {Element el = getElement(i);if(!set.contains(el)) {set.add(el);}if(set.contains(el.nextNode)) {return true;}}return false; }}