package com.itheima.demo1;
import java.util.Iterator;
import java.util.function.Consumer;
//带哨兵的单项链表
public class sentry implements Iterable<Integer> {
private Node head = new Node(0,null);//头指针
private static class Node {//内部类使用外部类的成员不加static
int value;//值
Node next;//下一个节点指针
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return "Node{value = " + value + ", next = " + next + "}";
}
}
//插入(向链表头部添加)
public void addFirst(int value) {
insert(0,value);
}
// //插入(向链表尾部添加)
// public void addLast(int value) {
// Node last = head;
// if (last == null) {
// addFirst(value);
// return;
// }
// while(last.next!=null){
// last=last.next;
// }
//
// last.next = new Node(value, last.next);
// }
//插入(向链表尾部添加)
public void addLast(int value) {
Node last = findLast();
last.next = new Node(value, last.next);
}
//找最后一个节点
private Node findLast() {
Node p = head;
while (p.next != null) {
p = p.next;
}
return p;
}
// public void test() {
// int i = 0;
// Node p = head;
// while (p != null) {
// System.out.println(i + ":" + p.value);
// i++;
// p = p.next;
// }
// }
//给定索引返回节点
private Node findNode(int index) {
int i = -1;
Node p = head;
while (p != null) {
if (index == i) {
return p;
}
i++;
p = p.next;
}
return null;
}
public int get(int index) {
Node node = findNode(index);
if (node == null) {
throw new IllegalArgumentException(
String.format("index[%d]不合法%n", index));
}
return node.value;
}
//遍历1
public void loop1(Consumer<Integer> consumer) {
Node p = head.next;
while (p != null) {
consumer.accept(p.value);
p = p.next;
}
}
//遍历2
public void loop2(Consumer<Integer> consumer) {
for (Node p = head.next; p != null; p = p.next) {
consumer.accept(p.value);
}
}
//遍历3
@Override
public Iterator<Integer> iterator() {
//匿名内部类
return new Iterator<Integer>() {
Node p = head.next;
@Override
public boolean hasNext() {//询问是否有下一个元素
return p != null;//是真,否假
}
@Override
public Integer next() {//返回当前元素值。,并指向下一个元素
int v = p.value;
p = p.next;
return v;
}
};
}
//向索引位置插入
public void insert(int index, int value) {
Node prev = findNode(index - 1);
if (prev == null) {
throw illegalIndex(index);
}
prev.next = new Node(value, prev.next);
}
private IllegalArgumentException illegalIndex(int index) {
return new IllegalArgumentException(
String.format("index[%d]不合法%n", index));
}
//删除第一个节点
public void removeFirst() {
remove(0);
}
//根据索引删除节点
public void remove(int index) {
Node prev = findNode(index - 1);
if (prev == null || prev.next == null) {
throw illegalIndex(index);
}
prev.next = prev.next.next;
}
}