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个节点。

每个节点包含valuenextvalue变量表示节点的值,next表示到下一个节点的链接。

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


示例 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中实现了链表。在这里,我们使用了该类提供的方法来添加元素和访问链表中的元素。

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

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战