import java.util.Iterator;
public class LinkList<T> implements Iterable<T>{
@Override
public Iterator<T> iterator() {
return new Literator();
}
private class Literator implements Iterator{
private Node n;
public Literator(){
this.n=head;
}
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public Object next() {
n=n.next;
return n.t;
}
}
private class Node {
T t;
Node next;
public Node(T t, Node next) {
this.t = t;
this.next = next;
}
}
private Node head;
private int N;
public LinkList() {
head = new Node(null, null);
N = 0;
}
public void clear() {
head.next = null;
this.N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int length() {
return N;
}
public T get(int i) {
Node n = head;
for (int index = 0; index <= i; index++) {
n = n.next;
}
return n.t;
}
public void insert(T t) {
Node n = head;
while (n.next != null) {
n = n.next;
}
Node newNode = new Node(t, null);
n.next = newNode;
N++;
}
public void insert(int i, T t) {
Node pre = head;
for (int j = 0; j <= i - 1; j++) {
pre = pre.next;
}
Node curr = pre.next;
Node newNode = new Node(t, curr);
pre.next = newNode;
N++;
}
public T remove(int i) {
Node pre = head;
for (int j = 0; j <= j - 1; j++) {
pre = pre.next;
}
Node curr = pre.next;
pre.next = curr.next;
N--;
return curr.t;
}
public int indexOf(T t) {
Node n = head;
for (int i = 0; n.next != null; i++) {
n = n.next;
if (n.t.equals(t)) {
return i;
}
}
return -1;
}
}
public class TestLinkList {
public static void main(String[] args) {
LinkList<String > linkList=new LinkList<>();
linkList.insert("a");
linkList.insert("b");
linkList.insert("c");
linkList.insert(1,"1.5");
for (int i = 0; i <linkList.length() ; i++) {
System.out.println(linkList.get(i));
}
System.out.println("_________________________________________________");
linkList.remove(0);
for (int i = 0; i <linkList.length() ; i++) {
System.out.println(linkList.get(i));
}
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-22159.html