初始化
两种
单链表的初始化我用了两种方法
方法一
调用Iterable接口,准备内部类,一个泛型的示例
定义头结点,长度
写节点类,构造器
重写接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public class LinkList<T> implements Iterable { private Node head; private int N; public class Node { T item; Node next; public Node(T item, Node next){ this.item = item; this.next = next; } } @Override public Iterator iterator(){ return new LIterator; } public class LIterator implements Iterator{ private LinkList.Node n; public LIterator(){ this.n = head; } public boolean hasNext{ return n.next!= null; } public Object next{ n = n.next; return n.item; } } }
|
方法二
先创建一个头结点,它是单链表的头,后面没添加一个结点就加入到链表的最后
写头结点类,这里是创建结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class HeroNode { int no; String name; String nickName; HeroNode next; public HeroNode(int no, String name, String nickname){ this.no = no; this.name = name; this.nickname = nickname; public String toString(){ return "no:" + no + " name:" + name + " nickname:"; } } }
|
初始化头结点,写各种方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class SingliLinkedList { private HeroNode head = new HeroNode(0, "", ""); public void add(HeroNode heroNode) { HeroNode temp = head; while(true) { if(temp.next == null){ break; } temp = temp.next; } temp.next = heroNode; } public void list(){ if(head.next == null){ System.out.println("链表为空"); return; } HeroNode temp = head.next; while(true){ if(temp == null){ break; } System.out.println(temp); temp = temp.next; } } }
|
写测试类
先创建结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class SingleLinkedListDemo { public static void main(String[] args){ HeroNode hero1 = new HeroNode(1, "原种无影", "爱梅特赛尔克"); HeroNode hero2 = new HeroNode(2, "维涅斯", "海德林"); HeroNode hero3 = new HeroNode(3, "食材", "拉拉肥"); SingleLinkList singleLinkedList = new SingleLinkedList(); singleLinkedList.add(hero1); singleLinkedList.add(hero2); singleLinkedList.add(hero3); singleLinkedList.list(); } }
|
删除结点
1 2 3 4 5 6 7
| public void removeIndex(int i){ Node pre = head; for (int index = 0; index <= i - 1; index ++){ pre = pre.next; } Node curr = pre.next; }
|
插入结点
1 2 3 4 5 6 7 8 9
| 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++; }
|
获取结点
1 2 3 4 5 6 7
| public T get(int i){ Node n = head.next; for(int index = 0; index < i; index++){ n = next; } return n.item; }
|
查找结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public int find(T t) { Node n = head; int i = 0; boolean flag = false; if (head == null) { System.out.println("List is empty"); }else{ while(n != null){ if(n.item == t){ flag = true; break; } i++; n = n.next; } } }
|