数据结构:无头单向链表的操作

一:什么是链表:

  • 链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的

(一):分类:

在这里插入图片描述

二:无头单向非循环链表实现

注:此处的head表示第一个节点,并不是有头链表。有头的链表的头是一个傀儡节点。
在这里插入图片描述

(一)、创建节点类

class ListNode{
   
    public int val;
    public ListNode next;
    public ListNode(int val){
   
        this.val=val;
    }
}

在这里插入图片描述

(二)、创建链表

public class MyLinkedList1{
   
    public ListNode head;//始终指向表头
    //实现各种中操作方法。
    }

(三)、尾插法

public class MyLinkList1{
   
    public ListNode head;
    public void lastNode(int data){
   
        ListNode node=new ListNode(data);
        ListNode cur=this.head;
        if(this.head==null){
   
            this.head=node;
            return;
        }
        while (cur.next!=null){
   
            cur=cur.next;//循环。
        }
        cur.next=node;
        node.next=null;
       }
  }

在这里插入图片描述

四、头插法

public void addFirst(int data){
   
        ListNode node=new ListNode(data);
        node.next=head;
        head=node;
    }

在这里插入图片描述

计算链表的长度

public int size(){
   
        int count=0;
        ListNode cur=this.head;
        while (cur!=null){
   
            count++;
            cur=cur.next;
        }
        return count;
    }

索引位置

//索引位置。//返回了一个节点cur.
    public ListNode findIndex(int index){
   
        ListNode cur=this.head;
        while (index-1!=0){
   
            cur=cur.next;
            index--;
        }
        return cur;
    }

在这里插入图片描述

任意位置插入

//任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
   
        if (index<0||index>size()){
   
            System.out.println("位置不合法");
            return;
        }
        if (index==0){
   
            addFirst(data);
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值