Java数据结构--链表

文章详细介绍了单链表的概念,强调其作为动态数据结构的优势和不足。接着,展示了如何创建Node类以及对链表进行增加、删除、查询、更新等操作的方法,包括使用虚拟头结点优化插入过程。同时,文章涵盖了链表的时间复杂度分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


前言

    单链表是一种链式存取的数据结构,链表中的数据是以结点来表示的,每个结点由元素和指针构成。
    元素表示数据元素的映象,就是存储数据的存储单元;指针指示出后继元素存储位置,就是连接每个结点的地址数据。
    以结点的序列表示的线性表称作线性链表,也就是单链表,单链表是链式存取的结构。


链表:真正的动态数据结构

 

一、链表

数据存储在"结点"(Node)中

优点:不需要处理固定容积问题,真正的动态
缺点:丧失了随机访问的能力

二、创建Node

public class LinkedList<T extends Comparable<T>> {

    //链表的相关属性
    private Node head;//链表的头
    private int size;//链表中结点的个数

    //创建Node  内部类
    private class Node {
        //结点中的内容
        T ele;
        //索引,指向下一个结点
        Node next;

        public Node(T ele) {
            this.ele = ele;
        }

        @Override
        public String toString() {
            return ele.toString();
        }
    }
    public LinkedList() {
        this.head = null;
        this.size = 0;
    }
}

三、对链表进行增加操作

//原始方法    
public void addHead(T ele) {
        //1.先创建结点
        Node node = new Node(ele);
        //2.node.next -> head
        node.next = head;
        //3.更新head到node
        head = node;
        //4.更新size
        this.size++;
    }
    //在头部添加结点
    public void addHead(T ele) {
        add(0,ele);
    }  

    //在链表的尾部添加
    public void addTail(T ele){
        add(this.size,ele);
    }    

    //在任意位置添加: 关键点:找到待添加位置的前一个结点
    public void add(int index,T ele) {
        if(index < 0 || index > this.size) {
            throw new IllegalArgumentException("index is invalid");
        }
        //1.创建结点
        Node node = new Node(ele);
        if(head == null) {
            head = node;
            this.size++;
            return;
        }
        //在索引为0的位置添加,因为头结点没有前置结点
        if(index == 0) {
            node.next = head;
            head = node;
            this.size++;
            return;
        }
        //2.找到待添加位置的前一个结点
        Node pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        //3.进行操作
        node.next = pre.next;
        pre.next = node;
        this.size++;
    }

四、使用虚拟头结点

 

    //在任意位置添加: 关键点:找到待添加位置的前一个结点
    public void add(int index,T ele) {
        if(index < 0 || index > this.size) {
            throw new IllegalArgumentException("index is invalid");
        }
        //(0) 创建虚拟头结点 dummyHead
        Node dummyHead = new Node(null);
        dummyHead.next = head;
        //1.创建结点
        Node node = new Node(ele);
        //2.找到待添加位置的前一个结点
        Node pre = dummyHead;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        //3.进行操作
        node.next = pre.next;
        pre.next = node;
        head = dummyHead.next;
        this.size++;
    }

五、链表的遍历、查询、更新操作

    //遍历链表
    public String showLinkedList() {
        //定义当前结点
        Node cur = head;
        StringBuilder sb = new StringBuilder();
        while(cur!=null) {
            sb.append(cur+"-->");
            //更新当前结点的值
            cur = cur.next;
        }
        return sb.toString();
    }

    //获取链表头的元素
    public T getHead() {
        return this.head == null ? null : this.head.ele;
    }

    //获取链表的最后一个元素
    public T getTail() {
        if (head == null) {
            return null;
        }
        Node cur = head;
        for (int i = 1; i < this.size; i++) {
            cur = cur.next;
        }
        return cur.ele;
    }

    //根据索引获取指定位置的内容
    public T get(int index) {
        if(index < 0 || index >= this.size){
            throw new IllegalArgumentException("index is invalid!");
        }
        if(head == null){
            return null;
        }
        Node cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur.ele;
    }


    //获取链表中结点的个数
    public int getSize() {
        return this.size;
    }
    //判断链表是否为空
    public boolean isEmpty() {
        return this.size == 0;
    }

    //判断指定的内容是否存在
    public boolean contains(T ele) {
        Node cur = head;
        while (cur != null) {
            if (cur.ele.compareTo(ele) == 0) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    //更新指定位置结点的内容
    public void set(int index,T ele){
        if(index < 0 || index >= this.size){
            throw new IllegalArgumentException("index is invalid!");
        }
        Node cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        cur.ele = ele;
    }

六、从链表中删除元素 

删除任意位置的结点:

    //删除任意位置的结点
    public T remove(int index) {
        if(index < 0 || index >= this.size) {
            throw new IllegalArgumentException("index is invalid!");
        }
        Node dummyHead = new Node(null);
        dummyHead.next = head;
        //找到删除结点的前置结点
        Node pre = dummyHead;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        //1.获取删除结点
        Node removeNode = pre.next;
        T result = removeNode.ele;
        this.size--;
        //2.删除
        pre.next = removeNode.next;
        removeNode.next = null;
        //3.重置头结点
        head = dummyHead.next;
        return result;
    }
//删除链表头结点
    public T removeHead(){
        /*if(head == null){
            return null;
        }
        T result = head.ele;
        head = head.next;
        this.size--;
        return result;*/
        return remove(0);
    }

    //根据内容来删除链表中的结点
    public void remove(T val){
        head = remove(head,val);
    }

    //从以node为头结点的链表中删除值为val的头结点
    private Node remove(Node node,T val){
        //1、递归终止的条件
        if(node == null){
            return null;
        }
        //2、递归操作
        if(node.ele.compareTo(val) == 0){
            return node.next;
        }else{
            node.next = remove(node.next,val);
            return node;
        }
    }

    //删除链表尾节点
    public T removeTail() {
        return remove(this.size-1);
        /*if(head == null) {
            return null;
        }
        Node pre = head;
        for (int i = 1; i < this.size-1; i++) {
            pre = pre.next;
        }
        Node node = pre.next;
        T result = node.ele;
        pre.next = node.next;
        node.next = null;
        this.size--;
        return result;*/
    }

七、链表的时间复杂度分析

添加操作:
       addList(e)        O(n)
       addFirst(e)       O(1)
       add(index,e)  O(n/2)= O(n)

删除操作:
       removeLst(e)            O(n)
       removeFirst(e)          O(1)
       remove(index)           O(n/2)=O(n)

修改操作      O(n)
        set(index,e)           O(n)

查找操作:
        get(index)                 O(n)
        contains(e)               O(n)
        find(e)                       O(n)
 

 

### Java 数据结构 链表 实现教程 #### 单链表的定义与基本实现 在 Java 中,单链表可以通过自定义类来实现。以下是基于引用的内容构建的一个完整的单链表实现方案。 ```java public class LinkedList { // 定义内部节点类 public static class Node { public int data; // 假设节点存储的数据类型为 int public Node next; public Node(int data) { this.data = data; this.next = null; } } private Node head = null; // 初始化头节点为空 // 添加节点的方法 public void addNode(int data) { Node newNode = new Node(data); if (head == null) { // 如果链表为空,则新节点作为头节点 head = newNode; } else { Node temp = head; while (temp.next != null) { // 找到最后一个节点 temp = temp.next; } temp.next = newNode; // 将新节点连接到最后一个节点之后 } } // 获取链表长度(不统计头节点) public int getLength() { if (head == null) { // 空链表返回 0 return 0; } int length = 0; Node current = head; while (current != null) { // 遍历整个链表 length++; current = current.next; } return length; } // 输出链表内容 public void displayList() { Node node = head; while (node != null) { System.out.print(node.data + " -> "); node = node.next; } System.out.println("null"); } } ``` 上述代码实现了单链表的基本功能,包括添加节点、计算链表长度以及打印链表内容的功能[^1]。 --- #### 链表的特点及其存储方式 链表是一种物理存储单元上非连续、非顺序的存储结构。它的特点是数据元素之间的逻辑顺序通过链表中的指针链接次序实现。具体来说,链表由一系列结点组成,每个结点包含两部分:一部分用于存储数据元素(即数据域),另一部分用于存储下一个结点地址(即指针域)。这种特性使得链表能够在运行时动态生成新的结点[^2]。 --- #### 计算链表的有效节点数量 为了获取单链表中有效节点的数量,可以采用以下方法: ```java public static int countNodes(Node head) { if (head == null || head.next == null) { // 判断是否为空链表或者只有一个头节点 return 0; } int count = 0; Node currentNode = head.next; // 不统计头节点本身 while (currentNode != null) { count++; currentNode = currentNode.next; } return count; } ``` 此函数能够有效地忽略头节点并仅统计实际有效的数据节点[^3]。 --- #### 遍历环形链表 如果需要处理的是环形链表,则其遍历方式略有不同。通常情况下,会利用辅助指针 `cur` 来完成这一操作。例如,在环形链表中找到某个特定条件下的节点或执行其他复杂操作时,可按照如下方式进行: ```java // 创建环形链表 public static void createCircularLinkedList(Node[] nodes) { for (int i = 0; i < nodes.length - 1; i++) { nodes[i].next = nodes[i + 1]; } nodes[nodes.length - 1].next = nodes[0]; // 形成闭环 } // 遍历环形链表 public static void traverseCircularList(Node first) { if (first == null) { return; } Node cur = first; do { System.out.print(cur.id + " -> "); cur = cur.next; } while (cur != first); // 当回到起点时停止 System.out.println(first.id); // 补充最后一个节点输出 } ``` 这段代码展示了如何创建和遍历环形链表的过程[^4]。 --- #### 总结 以上介绍了单链表的基础概念及其实现细节,并进一步探讨了如何计算链表长度以及遍历环形链表的具体方法。这些知识点构成了理解 Java 数据结构链表的核心基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叫我剑锋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值