import java.util.Iterator;
public class LinkList<T> implements Iterable<T>{
//整个链表反转
public void reverse(){
if(isEmpty()){
return;
}
reverse(head.next);
}
//节点反转
public Node reverse(Node curr){
if(curr.next==null){
head.next=curr;
return curr;
}
Node pre=reverse(curr.next);
pre.next=curr;
curr.next=null;
return curr;
}
@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; //链表长度+1
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++;
}
//删除指定位置i处的元素,并返回被删除的元素
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");
for (int i = 0; i < linkList.length(); i++) {
System.out.println(linkList.get(i));
}
System.out.println("_________________________________________________");
linkList.reverse();
for (int i = 0; i < linkList.length(); i++) {
System.out.println(linkList.get(i));
}
}
}