链接点以及链表实现

链接点

  • 链接点中包含一个数据域和一个指针域,其中数据域用来包装数据,而指针域用来指向下一个链接点
public class Link{
    //数据域
    private int data;

    //指针域
    private Link next;

    public Link(int data){
        this.data=data;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Link getNext() {
        return next;
    }

    public void setNext(Link next) {
        this.next = next;
    }
}

实现链表

  • 在插入节点到制定位置的部分,为什么只循环到pos-1
    这里写图片描述
    假如在下标2的位置插入数据,我们只需要找到1的下标在其后面插入数据即可。
public class LinkList{
    //开始节点
    private Link first;

    //添加
    public void insert(int value){
        Link lnk = new Link(value);
        if(first == null){
            first = lnk;
        }else{
            lnk.setNext(first);
            first = lnk;
        }
    }

    //显示全部
    public void display(){
        Link current = first;
        while(current != null){
            System.out.println(current.getData());
            current = current.getNext();
        }
    }

    //查找节点
    public Link find(int key){
        Link current = first;
        while(current.getData() != key){
            if(current.getNext() == null){
                return null;
            }
            current = current.getNext();
        }
    }

    //插入节点到指定位置
    public void insert(int value,int pos){
        if(pos == 0){
            insert(value);
        }else{
            Link current = first;
            for(int i=0;i<pos-1;i++){
                current = current.getNext();
            }
            Link lnk = new Link(value);
            lnk.setNext(current.getNext());
            current.setNext(lnk);
        }
    }

    //删除指定节点
    public void delete(int key){
        Link current = first;
        Link ago = first;
        while(current.getData() != key){
            if(current.getNext() == null){
                return;
            }else{
                ago = current;
                current = current.getNext();
            }
        }
        if(current == first){
            first = first.getNext();
        }else{
            ago.setNext(current.getNext());
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值