数据结构——链表

一、链表定义

链表是一种数据结构,和数组同级。比如,Java中我们使用的ArrayList,其实现原理是数组。而LinkedList的实现原理就是链表了。链表在进行循环遍历时效率不高,但是插入和删除时优势明显。下面对单向链表做一个介绍。

单向链表是一种线性表,实际上是由节点(Node)组成的,一个链表拥有不定数量的节点。其数据在内存中存储是不连续的,它存储的数据分散在内存中,每个结点只能也只有它能知道下一个结点的存储位置。由N各节点(Node)组成单向链表,每一个Node记录本Node的数据及下一个Node。向外暴露的只有一个头节点(Head),我们对链表的所有操作,都是直接或者间接地通过其头节点来进行的。

这里写图片描述

二、链表实现

package com.demo.node;

public class Test {

    private Node head = null;
    
    /**
     * 向链表中插入数据
     * @param d
     */
    public void addNode(Node node){
        Node temp = head;
        if(temp == null){
            head = node;
            return;
        }
        while(temp.next!=null){
            temp = temp.next;
        }
        temp.next = node;
    }
    
     /**
     * @param index:删除第index个节点
     * @return
     */
    public boolean deleteNode(int index){
        if(index<1 || index>length()){
            return false;
        }
        if(index == 1){
            head = head.next;
            return true;
        }
        int i = 0;
        Node preNode = head;
        Node curNode = preNode.next;
        while(curNode != null){
            if(i == index){
                preNode.next = curNode.next;
                return true;
            }
            preNode = curNode;
            curNode = curNode.next;
            i++;
        }
        return false;
    }
    
    public int length(){
        int length = 0;
        Node temp = head;
        while(temp!=null){
            temp = temp.next;
            length++;
        }
        return length;
    }
    
    public static void main(String[] args) {
        Test test = new Test();
        Node testNode1 = new Node(1);
        Node testNode2 = new Node(2);
        test.addNode(testNode1);
        test.addNode(testNode2);
        System.out.println(test.head.data+"->"+test.head.next.data);
    }
}
原文地址:https://www.cnblogs.com/zyxiaohuihui/p/8433200.html