【数据结构】单链表

10分钟学会单链表视频

单链表:一种链式的数据结构,每个数据相当于一个节点。(data,next)-(data,next)-(data,next)...
节点=元素+指针(data,next)
元素=节点中的真正数据(data);
指针指向下一个节点(next)。

单链表的优缺点                                 list集合优缺点

优点:插入删除速度快                      插入删除速度慢

缺点:取出数据慢                             取数数据快


为什么插入删除速度快?

因为next指向了下一个节点,假如有4个节点(1234),在3位置插入7,只需要更改7的next和2的next即可。

如果是list集合(1234),同样的操作,不仅插入了一个7,而且7后面的数据,实际上重新赋值了一次。

为什么取值速度慢?

因为每次都是从头结点开始查找,而list集合可以通过下标取值


public class Test {

    public static void main(String[] args) {
        add("1");//1
        add("2");//12
        add("3");//123
        add("4");//1234
        insert(3,"7");//12(7)34——>12734
    }

    private static String result2 = "";
    private static void insert(int index, String data) {
        if (null == head) throw new NullPointerException("No HeadNode Here!");
        Node current = head;
        int count = 1;//从1位置开始找
        while (current.next != null) {
            if (index == ++count) {//找到index的前一个位置(3的前面位置是2)
                Node inserNode = new Node(data);//插入节点
                inserNode.next = current.next;//inserNode节点的指针,指向后一个节点
                current.next = inserNode;//inserNode前面节点的指针,指向inserNode节点
                break;
            }
            current = current.next;//如果没找到,就继续轮循
        }
        current = head;//仅为打印
        while (current.next != null) {
            current = current.next;
            result2 += current.data;
        }
        System.out.println(result2);
    }

    private static String result = "";
    private static Node head;

    /**
     * 新增节点
     * @param data
     */
    private static void add(String data) {
        if (null == head) {
            head = new Node(data);//新建头结点,仅一次
            result = head.data;//仅为打印
        } else {
            Node current = head;
            //从头结点开始轮循
            while (current.next != null) {
                //如果有下个节点,继续轮循
                current = current.next;
            }
            //如果当前节点后面没有节点,当前节点的指针指向新建节点
            current.next = new Node(data);
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
            result += current.data;//仅为打印
        }
        System.out.println(result);
        result = head.data;
    }

    /**
     * 节点类
     */
    private static class Node {
        public String data;//节点数据
        public Node next;//指针,指向下一个节点(Node)
        public Node (String data) {
            this.data = data;
        }
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值