实现 LinkedList 的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:实现 LinkedList 的 Java 程序

public class LinkedList {

  // create an object of Node class
  // represent the head of the linked list
  Node head;

  // static inner class
  static class Node {
    int value;

    // connect each node to next node
    Node next;

    Node(int d) {
      value = d;
      next = null;
    }
  }

  public static void main(String[] args) {

    // create an object of LinkedList
    LinkedList linkedList = new LinkedList();

    // assign values to each linked list node
    linkedList.head = new Node(1);
    Node second = new Node(2);
    Node third = new Node(3);

    // connect each node of linked list to next node
    linkedList.head.next = second;
    second.next = third;

    // printing node-value
    System.out.print("LinkedList: ");
    while (linkedList.head != null) {
      System.out.print(linkedList.head.value + " ");
      linkedList.head = linkedList.head.next;
    }
  }
}

输出

LinkedList: 1 2 3

在上面的例子中,我们已经用 Java 实现了单向链表。这里,链表由 3 个节点组成。

每个节点由 valuenext . 这 value 变量代表节点的值, next 表示到下一个节点的链接。

要了解 LinkedList 的工作原理,请访问 LinkedList 数据结构

示例 2:使用 LinkedList 类实现 LinkedList

Java 提供了一个 LinkedList 可用于实现链表的构建类。

import java.util.LinkedList;

public class Main {
  public static void main(String[] args){

    // create a linked list using the LinkedList class
    LinkedList<String> animals = new LinkedList<>();

    // Add elements to LinkedList
    animals.add("Dog");

    // add element at the beginning of linked list
    animals.addFirst("Cat");

    // add element at the end of linked list
    animals.addLast("Horse");
    System.out.println("LinkedList: " + animals);

    // access first element
    System.out.println("First Element: " + animals.getFirst());

    // access last element
    System.out.println("Last Element: " + animals.getLast());
    }
}

输出

LinkedList: [Cat, Dog, Horse]
First Element: Cat
Last Element: Horse

在上面的例子中,我们在 Java 中使用了 LinkedList 类实现了链表。在这里,我们使用了类提供的方法从链表中添加元素和访问元素。

请注意,我们在创建链表时使用了尖括号 (<>)。它表示链表是泛型类型。