package algorithm2;
import java.util.Iterator;
public class LinkList implements Iterable{
//内部类
private class Node{
private T item;
private Node next;
public Node(T t,Node next) {
this.item = t;
this.next = next;
}
}
//成员变量
private Node head;
private int N;
//构造方法
public LinkList(){
//初始化头结点
this.head = new Node(null,null);
//初始化元素个数
this.N = 0;
}
//成员方法
//清空链表
public void clear() {
head.next = null;
this.N = 0;
}
//获取链表长度
public int length() {
return N;
}
//判断链表是否为空
public boolean isEmpty() {
return N==0;
}
//获取指定位置i处的元素
public T get(int i) {
//通过循环,从头结点找i次,就可以找到元素
Node n = head;
for (int index = 0; index <=i;index ++) {
n=n.next;
}
return n.item;
}
//向链表中插入元素
public void insert(T t) {
//找到当前链表的最后一个结点
Node n = head;
while(n.next!=null) {
n=n.next;
}
//创建新节点
Node node = new Node(t,null);
//让当前最后一个结点指向新节点
n.next = node;
//元素的个数加1
N++;
}
//在指定位置i处插入元素t;
public void insert(int i,T t) {
//找到i-1位置的结点
Node n =head;
for (int index = 0; index <= i-1; index++) {
n=n.next;
}
//现在这个n是i-1位置的结点
//创建一个新节点,指向i位置的结点
Node newNode = new Node(t,n.next);
//让i-1位置的结点指向新结点
n.next = newNode;
N++;
}
//删除i位置的结点,并返回删除的元素
public T remove(int i) {
Node n =head;
//找到i-1位置的结点
for (int index = 0; index <= i-1; index++) {
n=n.next;
}
Node curr = n.next;
Node xia = curr.next;
n.next=xia;
N--;
return curr.item;
}
//查找某元素第一次出现的位置
public int indexOf(T t) {
Node n =head;
for (int i =0; n.next != null; i++) {
n=n.next;
if (n.item==t) {
return i;
}
}
return -1;
}
@Override
public Iterator iterator() {
return new IteratorImpl();
}
private class IteratorImpl implements Iterator {
//定义成员变量
private Node n;
int N;
public IteratorImpl() {
this.n=head;
N=0;
}
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public Object next() {
n=n.next;
return n.item;
}
}
}