Java教程

Java 实现 LinkedList 的程序

实现LinkedList的Java程序

在这个例子中,我们将学习用 Java 实现链表数据结构。
要理解此示例,您应该了解以下Java 编程主题:
Java LinkedList Java 泛型

示例1: 实现LinkedList的Java程序

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 Data Structure。

示例2: 使用LinkedList类实现LinkedList

Java 提供了一个内置的 LinkedList 类,可用于实现链表。
import java.util.LinkedList;
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
在上面的例子中,我们使用了 LinkedList 类在Java 中实现了链表。在这里,我们使用了类提供的方法从链表中添加元素和访问元素。
注意,我们在创建链表时使用了尖括号()。表示链表是泛型类型。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4