package linkList;
import java.util.Iterator;
public class LinkList<T> implements Iterable<T> {
//记录头节点
private Node head;
//记录链表的长度
private int N;
//节点类
private class Node{
//存储数据
T item;
//下一个节点
Node next;
public Node(T item,Node next){
this.item=item;
this.next=next;
}
}
public LinkList(){
//初始化头节点
this.head=new Node(null,null);
//初始化元素个数
this.N=0;
}
//清空链表
public void clear(){
head.next=null;
this.N=0;
}
//获取链表长度
public int length(){
return N;
}
//判断链表是否为空
public boolean isEmpty(){
return N==0;
}
//获取指定位置处的元素
public T get(int i){
//通过循环,从头节点开始往后找,依次找i次就可以找到对应元素
Node n=head.next; //第一个元素的位置
//遍历i次
for(int index=0;index<i;index++){
n=n.next;
}
return n.item;
}
//向链表中添加元素
public void insert(T t){
//找到当前链表最后一个节点
Node n=head;
while(n.next!=null){
n=n.next;
}
//创建新节点,保存元素t
Node newNode=new Node(t,null);
//让当前元素最后一个节点指向新节点
n.next=newNode;
//元素个数+1
N++;
}
//向指定位置i处添加元素
public void insert(int i,T t){
//找到i位置前一个节点
Node pre=head;
for(int index=0;index<i;index++){
pre=pre.next;
}
//找到i位置的节点
Node curr=pre.next;
//创建新节点,并且新节点需要指向原来i位置的节点
Node newNode=new Node(t,curr);
//原来i位置的前一个节点指向新节点即可
pre.next=newNode;
//元素个数+1
N++;
}
//删除指定位置的元素,并返回被删除的元素
public T remove(int i){
//找到i位置的前一个节点
Node pre=head;
for(int index=0;index<i;index++){
pre=pre.next;
}
//找到i位置的节点
Node curr=pre.next;
//找到i位置的下一个节点
Node nextNode=curr.next;
//前一个节点指向下一个节点
pre.next=nextNode;
//元素个数-1
N--;
return curr.item;
}
//找到元素t第一次在链表中出现的位置索引
public int indexOf(T t){
//从头节点开始依次遍历每一个节点,取出item和t进行比较,如果相同,就找到了
Node n=head;
for(int i=0;n.next!=null;i++){
n=n.next;
if(n.item.equals(t)){
return i;
}
}
return -1;
}
/*
* (non-Javadoc)
* @see java.lang.Iterable#iterator()
* 以下关于iterator的操作是为了实现链表的遍历而实现的接口
*/
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new LIterator();
}
private class LIterator implements Iterator{
/*
* (non-Javadoc)
* @see java.util.Iterator#hasNext()
* 实现链表遍历
*/
private Node n;
public LIterator() {
// TODO Auto-generated constructor stub
this.n=head;
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return n.next!=null;
}
@Override
public Object next() {
// TODO Auto-generated method stub
n=n.next;
return n.item;
}
}
}
数据结构之单链表的实现(Java版本)
最新推荐文章于 2022-09-06 22:08:09 发布