Java单链表

本文介绍了单链表的概念,以及三种链表插入方法:头插法、尾插法和插入指定位置,并配合示意图进行说明,最后提供了相应的代码实现。
摘要由CSDN通过智能技术生成

单链表

单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。
这里写图片描述

链表的插入

(1)头插法

看图看图

这里写图片描述

(2)尾插法

看图看图
这里写图片描述

(3)插入指定位置

看图看图
这里写图片描述

代码

class TestLink{

    private Entry head;//指向头结点的引用

    public TestLink(){//创建头结点
        head = new Entry();
    }

    class Entry{ //实例内部类
        int data;//结点数据
        Entry next;//结点地址

        public Entry(){
            data = -1;
            next = null;
        }

        public Entry(int val){
            data = val;
            next = null;
        }

    }
    //头插法
    public void insertHead(int val){
        //有这么一个节点
        Entry cur = new Entry(val);
        cur.next = head.next;
        head.next = cur;
    }
    //尾插法
    public void insertTail(int val){
        Entry cur  = head;
        while(cur.next!=null){
            cur = cur.next;
        }
        Entry entry= new Entry(val);
        cur.next = entry;
    }
    //求长度
    public int getLength(){
        int len = 0;
        Entry cur = head.next;
        while(cur != null){
            len++;
            cur = cur.next;
        }
        System.out.println("length: "+len);
        return len;
    }
    //将val插入指定位置
    public boolean insertPos(int val,int pos){
        if(pos < 0 || pos >= getLength()+1){
            return false;
        }
        Entry cur = head;
        for(int i = 0;i<=pos-1;i++){
            cur = cur.next;
        }
        Entry entry = new Entry(val);
        entry.next = cur.next;
        cur.next = entry;
        return true;
    }

    public void show(){
        Entry cur  = head.next;
        while(cur != null){
            System.out.println(cur.data+" ");
            cur = cur.next;
        }
    }

}
public class TestDemo1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TestLink testLink = new TestLink();
        testLink.insertTail(10);
        testLink.insertTail(20);
        testLink.insertPos(30, 0);
        testLink.insertPos(40, 0);
        testLink.show();
        testLink.getLength();
    }

}

运行结果:
这里写图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值