java数据结构-链表的实现

//链表的实现主要是由链节点不断相连而构成


class Link{//链节点
public int data;//数据项
public Link next;//引用,指向下一个链节点,初始为NULL

public Link(int d){
data=d;
next=null;
}
public void showLink(){
System.out.println("{"+data+"}");
}



}






class LinkList{//链表,只包含first
public Link first;

public void insert(int data){//插入一个链节点,总是从链首插入
Link newLink=new Link(data);
newLink.next=first;
first=newLink;

}
public Link delete(){//删除一个链节点,总是从头删除
Link tmp=first;
first=first.next;
return tmp;
}

public void show(){//显示链表
Link current=first;
while(current!=null){
current.showLink();
current=current.next;
}
}
public boolean isEmpty(){
return first==null;
}
public boolean searchKey(int key){
if(!isEmpty()){
Link current=first;
Link prior;
while(current!=null){
if(current.data==key)
return true;
else{
prior=current;
current=current.next;
}
}
return false;
}
return false;
}
public Link deleteKey(int key){
Link current=first;
Link prior=first;
Link tmp=null;
if(!isEmpty()){
while(current!=null){
if(current.data==key)
break;
else{
prior=current;
current=current.next;
}
}
}
if(current==first){
first=first.next;
}
if(current!=null){
tmp=current;
prior.next=current.next;
}
return tmp;
}
public void insertRear(int data){
Link newLink=new Link(data);
if(first==null)
first=newLink;
else{
Link current=first;

while(current.next!=null){
current=current.next;
}



current.next=newLink;
}
}


}


public class LinkListTest{
public static void main(String[] args){
LinkList  ll=new LinkList();

ll.insertRear(10);
ll.insertRear(50);
ll.insertRear(20);
ll.insertRear(30);
ll.show();
/*
ll.insert(10);
ll.insert(50);
ll.insert(20);
ll.insert(30);
ll.show();
System.out.println("-------------------------------");
ll.delete();
ll.show();
System.out.println("----------好玩---------------------");
System.out.println(ll.searchKey(20));
System.out.println(ll.deleteKey(50));
System.out.println("----------好玩---------------------");
ll.show();*/
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值