Java写的一个LinkedList
MyLinkList实现代码
package MyLinkedList; import java.lang.reflect.ParameterizedType; public class MyLink <T> { private Entity<T> header; private int size; public MyLink() { this.header = new Entity(null,null,null); this.size = 0; this.header.next = (this.header.previous=this.header); } public void add(T entity) { //新节点的prev指向头结点 , 新节点的next指向头结点next Entity newNode = new Entity(header,entity,header.next); //头结点后面原来的节点的prev指向新节点 this.header.next.previous = newNode; //头结点的next指向新节点 this.header.next = newNode; size++; } public void delete(T paramObject) { Entity local; for(local = this.header.next;local!=this.header;local = local.next) { if(paramObject.equals(local.element)) { local.next.previous = local.previous; local.previous.next = local.next; local.previous = null; size--; break; } } } public int indexOf(T paramObject) { int i = 0; Entity local; for(local = this.header.next;local!=this.header;local = local.next) { if(paramObject.equals(local.element)) return i; i++; } return -1; } public T getElement(int paramInt) { return getEntity(paramInt).element; } private Entity<T> getEntity(int paramInt) { Entity local = this.header; if(paramInt>=0&¶mInt<this.size) { for(int i=0;i<=paramInt;i++) local = local.next; } return local; } public int getLength() { return this.size; } private class Entity<T> { T element; Entity<T> next; Entity<T> previous; public Entity(Entity<T> previous,T element,Entity<T> next) { this.element = element; this.next = next; this.previous = previous; } } }
测试用例
package MyLinkedList; import org.junit.Test; public class Client { MyLink<Model> list = new MyLink(); @Test public void test() { list.add(new Model("tom",18)); list.add(new Model("jeck",22)); list.add(new Model("asd",21)); list.add(new Model("toem",19)); Model m = new Model("zen",17); list.add(m); list.add(new Model("wen",23)); list.add(new Model("baobo",18)); list.add(new Model("dawei",20)); list.delete(m); System.out.println(list.getLength()); for(int i=0;i<list.getLength();i++) System.out.println(list.getElement(i).getName()+" "); } }
Model类
package MyLinkedList; public class Model { private String name; private int age; public Model(String name,int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }