import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Objects;
public class DanLianBiao<E> {
private Node<E> first;
public DanLianBiao() //初始化 实例单链表对象
{
first=new Node<>(null,null);
}
public void put(E e){ //添加元素
Node<E> curr=first;
while (curr.next!=null){
curr=curr.next;
}
curr.next=new Node<E>(e,null);
}
public void out(){ //输出元素
Node<E> curr=first;
while (curr.next!=null) {
curr=curr.next;
System.out.println(curr.e); }
}
public E RemoveFirst(){ //从前删除 并且返回最前面的值
E remove;
if(first.next!=null) {
remove=first.next.e;
first.next = first.next.next;
return remove;
}
throw new NoSuchElementException();
}
public boolean isExist(E e){ //元素是否存在
Node<E> curr=first;
while (curr.next!=null)
{
boolean bool=Objects.equals(curr.next.e,e);
if(bool)
return bool;
curr=curr.next;
}
return false;
}
public boolean isEmpty() //元素是否为空
{
return first.next==null;
}
private static class Node<E>{ //创建Node类 类部节点
E e;
Node<E> next;
Node(E e,Node<E> next){
this.e=e;
this.next=next;
}
}
}
java实现单链表(删除时超过链表范围则抛出NoSuchElementException()异常)
最新推荐文章于 2024-02-28 22:27:35 发布
这篇文章介绍了如何使用Java实现一个简单的单链表,包括元素的添加(put)、输出(out)、首元素删除(RemoveFirst)以及元素存在判断(isExist)。同时涵盖了判断链表是否为空(isEmpty)的功能。
摘要由CSDN通过智能技术生成