创建一个链表

本文介绍了链表的相关操作。首先创建接口并定义链表方法,接着创建类继承接口并实现方法。详细阐述了链表节点的定义,以及头插法、尾插法、任意位置插入等插入操作,还包含查找关键字、删除指定关键字节点等内容。

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

在创建一个链表之前,我们先传建一个接口,如图所示:
在这里插入图片描述
点击OK,这时我们已经创建好了一个接口,我们要在接口中写链表的一些方法:
在这里插入图片描述
此时,我们应该创建一个类,来继承这个接口,在类中重写这些函数:
在这里插入图片描述
这时我们把鼠标放在波浪线上点击alt加enter进行重写这些函数。
链表是有节点组成,每个节点上有data和next。首先我们需要定义这些:
在这里插入图片描述
1.头插法:
我们先定义一个节点,判断链表是否为空,若为空,此节点就为头结点,否则让此节点的next等于原链表的头结点,头结点等于此节点。
在这里插入图片描述
2.尾插法
我们先定义一个节点,判断链表是否为空,若为空,此节点就为头结点,也是为节点。否则,我们再定义一个节点,用它来遍历链表找到链表的尾节点,让尾节点的next为此节点。
在这里插入图片描述
3.任意位置插入,第一个数据节点为0号下标

public boolean addIndex(int index, int data) {
if (index == 0) {
addFirst (data) ;
return true;
}
Node node=new Node(data);
Node cur=searchIndex(index);
return false;
}
private void checkIndex(int index){
if(index0){
}
}
private Node searchIndex(int index){
Node cur=this.head;
int count=0;
while(count<index-1){
cur=cur.next;
count++;
}
return cur;
}
4.查找是否包含关键字key是否在单链表当中
public boolean contains(int key) {
Node cur=this.head;
while(cur!=null){
if(cur.data
key){
return true;
}
cur=cur.next;
}
return false;
}
5.删除第一次出现关键字为key的节点
private Node searchPre(int key){
Node pre=this.head;
if(pre.datakey){
return this.head;
}
while(pre.next!=null){
if(pre.next.data
key){
return pre;
}
pre=pre.next;
}
return null;
}
@Override

public int remove(int key) {
    int oldData=0;
    Node pre=searchPre(key);
    if(pre==null){
        throw new UnsupportedOperationException("不存在key");
    }
    //是头结点的时候
    if(pre==head&&pre.data==key){
        oldData=this.head.data;
        this.head=this.head.next;
        return oldData;
    }
    Node del=pre.next;
    oldData=del.data;
    pre.next=del.next;
    return oldData;
}

6.删除所有值为key的节点
public void removeAllKey(int key) {
    if(this.head==null){
        return;
    }
    Node pre=this.head;
    Node cur=pre.next;
    while(cur!=null){
        if(cur.data==key){
            cur=cur.next;
        }
        pre.next=cur;
        cur=cur.next;
    }
    if(head.data==key){
        head=this.head.next;
    }
}

7.得到单链表的长度

public int getLength() {
int count=0;
Node cur=this.head;
while(cur!=null){
count++;
}
//write
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值