单向链表的遍历、插入、查找、删除、搜索结点
import java.util.Iterator;
import java.util.function.Consumer;
public class SinglyLinkedList implements Iterable<Integer>{
private Node head=new Node(666,null);
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
SinglyLinkedList.Node p=head.next;
@Override
public boolean hasNext() {
return p!=null;
}
@Override
public Integer next() {
int v=p.value;
p=p.next;
return v;
}
};
}
private static class Node{
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
public void addFirst(int value){
insert(0,value);
}
public void loop1(Consumer<Integer>consumer){
Node p=head.next;
while(p!=null){
consumer.accept(p.value);
p=p.next;
}
}
public void loop2(Consumer<Integer>consumer) {
for (Node p=head;p!=null;p=p.next){
consumer.accept(p.value);
}
}
public void loop3(Consumer<Integer>before,
Consumer<Integer>after){
recursion(head,before,after);
}
private void recursion(Node curr,
Consumer<Integer> before, Consumer<Integer> after){
if(curr==null){
return;
}
before.accept(curr.value);
recursion(curr.next, before, after);
after.accept(curr.value);
}
private Node findLast() {
Node p;
for (p = head.next; p.next != null; p = p.next) {
}
return p;
}
public void addLast(int value){
Node last=findLast();
last.next=new Node(value,null);
}
public void test(){
int i=0;
for(Node p=head;p!=null;p=p.next,i++){
System.out.println(p.value+"索引是"+i);
}
}
private Node findNode(int index){
int i=-1;
for(Node p=head.next;p!=null;p=p.next,i++){
if(i==index){
return p;
}
}
return null;
}
public int get(int index) {
Node node = findNode(index);
if (node == null) {
try {
throw new IllegalAccessException(
String.format("index [%d] 不合法%n", index));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return node.value;
}
public void insert(int index,int value){
Node prev=findNode(index-1);
if(prev==null) {
try {
throw new IllegalAccessException(
String.format("index [%d] 不合法%n", index));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
prev.next=new Node(value,prev.next);
}
public void removeFirst(){
if(head==null) {
}
head=head.next;
}
public void remove(int index){
Node prev=findNode(index-1);
if(prev==null){
}
Node removed = prev.next;
if(removed==null){
}
prev.next=removed.next;
}
}