返回

深入理解链表设计之 Leetcode 707

前端

绪言

数据结构是计算机科学的基础,链表作为一种重要的数据结构,因其存储的灵活性、插入和删除的便捷性而广泛应用于各类场景。Leetcode 707 题正是考察链表的典型题目,旨在帮助程序员理解链表的基本操作和设计思路。

问题陈述

Leetcode 707 题要求设计一个链表类,并实现以下功能:

  • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回 -1。

链表类设计

为了解决 Leetcode 707 题,我们需要设计一个链表类,以满足题目要求。链表类的基本结构如下:

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

class LinkedList {
    ListNode head;

    // 在链表头部添加节点
    void addFirst(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = head;
        head = newNode;
    }

    // 在链表尾部添加节点
    void addLast(int val) {
        ListNode newNode = new ListNode(val);
        if (head == null) {
            head = newNode;
            return;
        }
        ListNode current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    // 获取链表中第 index 个节点的值
    int get(int index) {
        if (index < 0 || index >= size()) {
            return -1;
        }
        ListNode current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current.val;
    }

    // 获取链表长度
    int size() {
        int count = 0;
        ListNode current = head;
        while (current != null) {
            count++;
            current = current.next;
        }
        return count;
    }
}

算法分析

链表类的核心操作是 get(index) 方法,该方法用于获取链表中第 index 个节点的值。该方法首先判断 index 是否有效,如果 index 小于 0 或大于链表长度,则返回 -1。

如果 index 有效,则从链表头部开始遍历,并依次比较每个节点的索引值。当遇到索引值等于 index 的节点时,返回该节点的值。

代码示例

public class Main {

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.addFirst(1);
        list.addLast(2);
        list.addLast(3);

        System.out.println(list.get(0)); // 输出:1
        System.out.println(list.get(1)); // 输出:2
        System.out.println(list.get(2)); // 输出:3
        System.out.println(list.get(3)); // 输出:-1
    }
}

总结

Leetcode 707 题考察了链表的基本操作和设计思路。通过实现链表类,我们掌握了链表的存储结构和基本操作,并理解了链表的应用价值。