数据结构 链表的各种插入

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

链表的任意的位置插入时间复杂度都是O(1),没有增容问题,插入一个就开辟一个空间,这是链表相对于顺序表的优点,那么我们就来看看这个各种插入是怎样插入的。

1.中间位置插入

在这里插入图片描述

    public static Node MidInsertion(Node head,Node Insert,int index){
        Node cur = head;
        if(index<1||index>Length(head))//插入位置越界了,位置不能是头部
            return cur;
        for (int i=0;i<index-1;i++){
            cur=cur.next;
        }
        Insert.next=cur.next;
        cur.next=Insert;
        return cur;
    }

因为输入了要插入位置的下标,那就得到个位置结束for循环,这时候cur就指向该下标的的节点了,这时候修改要插入的节点的指向就可以了,注意这里修改的循序不能打乱。

2.头部插入

    public static Node HeadInsertion(Node head,Node Insert){
        Node cur = head;
        Insert.next=cur;
        cur=Insert;
        return cur;
    }

头部插入这里只需要更改指向就可以了,不用在进行遍历了,使头结点的引用指向要插入的结点,插入的节点的next指向原来的头结点。

3.尾部插入

    public static Node LastInsertion(Node head,Node Insert){
        Node cur=head;
        while(cur.next!=null){
            cur=cur.next;
        }
        cur.next=Insert;
        return head;
    }

尾插入需要先走到链表的末尾,然后只要让原来指向null的最后一个节点,指向要插入的节点就可以了。

验证

    public static void main(String[] args) {
        Node head=GreateLink();
        print(head);
        Node Insert=new Node(10);
        MidInsertion(head,Insert,3);
        print(head);

        Node Insert1=new Node(10);
        head=HeadInsertion(head,Insert1);
        print(head);
        
        Node Insert2=new Node(10);
        LastInsertion(head,Insert2);
        print(head);
    }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值