Java数据结构之链表:简单链表的实现

本文介绍了一个简单的单链表实现方法,包括插入、删除节点等基本操作,并演示了如何在Java中使用这些方法来管理和操作链表。此外,还讨论了如何查找特定元素并进行删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Link{
int iData;
double dData;
public Link(int iData,double dData){
this.iData = iData;
this.dData = dData;
}
Link next;

}
public class LinkList1 {
private Link first;
public void insert(int iData ,double dData){
Link newLink = new Link(iData , dData);
newLink.next = first;
first = newLink;
System.out.println(“一个节点被成功插入”);
}
public Link delete(){
Link temp = first;
first = temp.next;
System.out.println(“一个节点被成功删除”);
return temp;
}
public void disPlay(){
Link current = first;
if(current == null){
System.out.println(“当前链表为空”);
}else{
while(current != null){
System.out.println(“{” + “iData:” + current.iData + “,dData:” + current.dData + “}”);
current = current.next;
}
}
}
public boolean isEmpty(){
return (first == null);
}
}

public class UseLinkList1 {

public static void main(String[] args) {
    LinkList1 ll1 = new LinkList1();
    ll1.insert(3, 2.4);
    ll1.insert(5, 6.4);
    ll1.insert(7, 8.4);

    ll1.disPlay();

    ll1.isEmpty();

    ll1.delete();

    ll1.disPlay();

    ll1.delete();
    ll1.delete();

    ll1.isEmpty();

    ll1.disPlay();


}

}

/*可以看出,这种简单链表的实现其实是通过操纵引用实现的
特别是引用first,具体的过程大概是这样的,在插入第一个节点的
时候,引用first指向的是自身,而当继续插入节点时,就用first
指向新插入的节点,而用新插入的节点的next引用指向第一个被插入
的节点*/

//查找与删除指定元素的操作就稍微有些麻烦
public Link find(int key){
Link current = first;
while(current != null){
if(current.iData == key){
System.out.println(“找到了您要查询的节点”);
System.out.println(“您要查询的节点的信息为” + “{” +
“iData:” + current.iData + “,dData:” + current.dData + “}” );
return current;
}else{
current = current.next;
}
}
System.out.println(“对不起,该列表中没有您要查询的元素”);
return null;

}

/*return带代表的是方法的结束,因此尽管从表面上看我的代码似乎要经历更多的循环次数,但实际上两者是一样的,
但我的代码问题在于,我的整个代码基本是很难跳出while循环的,这样即使找到了目标元素,也很难对它进行进一步
的操作,也就是我的代码其实是只能查询,不能操作,而书中的代码对我而言具有很好的学习意义*/

public Link find(int key){
Link current = first;
while(current.iData != key){
if(current.next == null){
System.out.println(“对不起,没有找到您要查找的元素”);
return null;
}else{
current = current.next;
}
}
System.out.println(“您要查询的节点的信息为” + “{” +
“iData:” + current.iData + “,dData:” + current.dData + “}” );
return current;

public Link deleteEle(int key){
Link current = first;
Link previous = first;
while(current.iData != key){
if(current.next == null){
System.out.println(“没有找到您要删除的元素”);
return null;
}else{
previous = current;
current = current.next;
}
}
if(current == first){
first = first.next;
System.out.println(“{” + “iData:” + current.iData + “,dData:” + current.dData + “}被删除”);
return current;
}else{
previous.next = current.next;
current.next = null;
System.out.println(“{” + “iData:” + current.iData + “,dData:” + current.dData + “}被删除”);
return current;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值