/*数据结构单向链表基本操作
节点类
*/
import java.util.Iterator;
import java.util.function.Consumer;
public class shujujiegou implements Iterable<Integer> {//整体
private Node head;//头指针
@Override
public Iterator<Integer> iterator() {
//匿名内部类->带名字的内部类
return new NodeIterator();
}
private class NodeIterator implements Iterator<Integer> {
Node p=head;
@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) {
//1.链表为空
// head=new Node(value,null);
//2.链表非空(头插)
head = new Node(value, head);
}
//遍历链表
//Params:consumer-要执行的操作
public void loop(Consumer<Integer> consumer) {
Node p = head;
while (p != null) {
consumer.accept(p.value);
p = p.next;
}
}
//遍历链表2
//Params:consumer-要执行的操作
public void loop2(Consumer<Integer> consumer) {
for (Node p = head; p != null; p = p.next){
consumer.accept(p.value);
}
}
private Node findLast(){
if(head==null){
return null;
}
Node p;
for(p=head;p.next!=null;p=p.next){
}
return p;
}
public void addLast(int value){
Node last=findLast();
if(last==null){
addFirst(value);
return;
}
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);
}
根据索引查找
Params:index-索引
Returns:找到,返回该索引位置节点的值
Throws:IlLegalArgumentException-找不到,抛出index非法异常
}*/
private Node findNode(int index){//给定索引位置
int i=0;
for(Node p=head;p!=null;p=p.next,i++){
if(i==index){
return p;
}
}
return null;//没找到
}
public int get(int index) throws IllegalAccessException {
Node node=findNode(index);
if(node==null){
//抛异常
illegalIndex(index);
}
return node.value;
}
//异常处理(重点)
private static void illegalIndex(int index) throws IllegalAccessException {
throw new IllegalAccessException(
String.format("index[%d] 不合法%n", index)
);
}
/*
向索引位置插入
*/
public void insert(int index,int value) throws IllegalAccessException {
if(index==0){
addFirst(value);
return;
}
Node prev=findNode(index-1);//找到上一个节点
if(prev==null){
illegalIndex(index);
}
prev.next=new Node(value,prev.next);
}
//1.问题
//删除头节点
public void removeFirst() throws IllegalAccessException {
if(head==null) {
illegalIndex(0);
}
head=head.next;
}
public void remove(int index) throws IllegalAccessException {
if(index==0){
removeFirst();
return;
}
Node prev=findNode(index-1);//上一个节点
if(prev==null){
illegalIndex(index);
}
Node removed=prev.next;//被删除的节点
if(removed==null){
illegalIndex(index);
}
prev.next=removed.next;
}
}
标签:Node,index,null,value,next,链表,基本操作,数据结构,public
From: https://www.cnblogs.com/3-6-8/p/17542399.html