package 链表;
import java.util.Iterator;
public class SingleLink implements Iterable{
private int size;
private Node first;//首节点
/**
*
* 节点内部类
*
*/
private class Node{
Object data;
Node next;
public Node(Object data,Node next){
this.data=data;
this.next=next;
}
}
/**
* 根据指定索引查找节点
* @param index
* @return
*/
private Node node(int index){
Node c=first;
for(int i=0;i<index;i++){
c=c.next;
}
return c;
}
/**
* 添加方法
* @param obj
*/
public void add(Object obj){
Node newNode=new Node(obj,null);
if(first==null){
first=newNode;
}else{
Node last=node(size-1);
last.next=newNode;
}
size++;
}
public Object get(int index){
this.checkIndex(index);
return node(index).data;
}
/**
* 检查下标是否正确的方法
* @param index
*/
private void checkIndex(int index){
if(index<0){
throw new IndexOutOfBoundsException("is negative number! "+index);
}
if(index>=size){
throw new IndexOutOfBoundsException("index out of bounds "+index);
}
}
/**
* 返回大小的方法
* @return
*/
public int size(){
return size;
}
private class Iter implements Iterator{
private Node cNode=first;
private int cursor=0;
@Override
public boolean hasNext() {
return cursor!=size;
}
@Override
public Object next() {
Object o=cNode.data;
cNode=cNode.next;
cursor++;
return o;
}
}
@Override
public Iterator iterator() {
return new Iter() ;
}
/**
* 在指定位置插入一个新的节点
* @param obj
*/
public void insert(Object obj,int index){
this.checkIndex(index);
if(index==0){
Node newNode=new Node(obj,first);
first=newNode;
}else{
Node target=node(index);
Node newNode=new Node(obj,target);
Node pre=node(index-1);
pre.next=newNode;
}
size++;
}
/**
* 删除指定位置节点
* @param index
*/
public void delete(int index){
this.checkIndex(index);
Node target=node(index-1);
target.next=target.next.next;
size--;
}
}
单向链表
最新推荐文章于 2023-07-26 00:47:03 发布