📜  Java中的链表

📅  最后修改于: 2022-05-13 01:55:05.299000             🧑  作者: Mango

Java中的链表

链表是存在于Java.util 包中的 Collection 框架的一部分。此类是 LinkedList 数据结构的实现,它是一种线性数据结构,其中元素不存储在连续的位置,每个元素都是具有数据部分和地址部分的单独对象。元素使用指针和地址链接。每个元素称为一个节点。由于插入和删除的动态性和易用性,它们比数组更受欢迎。它也有一些缺点,比如节点不能直接访问,而是我们需要从头开始,通过链接到达我们希望访问的节点。

LinkedList 如何在内部工作?

由于 LinkedList 充当动态数组,并且我们不必在创建它时指定大小,因此当我们动态添加和删除项目时,列表的大小会自动增加。而且,元素不是以连续方式存储的。因此,没有必要增加尺寸。在内部,LinkedList 是使用双向链表数据结构实现的。普通链表和双向链表的主要区别在于双向链表包含一个额外的指针,通常称为前一个指针,以及单链表中的下一个指针和数据。

LinkedList 中的构造函数

为了创建 LinkedList,我们需要创建 LinkedList 类的对象。 LinkedList 类由各种允许创建列表的构造函数组成。以下是此类中可用的构造函数:

1. LinkedList():该构造函数用于创建一个空的链表。如果我们希望创建一个名为 ll 的空 LinkedList,则可以将其创建为:

LinkedList ll = new LinkedList();  

2. LinkedList(Collection C):此构造函数用于创建一个有序列表,其中包含指定集合的所有元素,由集合的迭代器返回。如果我们希望创建一个名为 ll 的 LinkedList,则可以将其创建为:

LinkedList ll = new LinkedList(C);

Java LinkedList 的方法

MethodDescription
add(int index, E element)This method Inserts the specified element at the specified position in this list.
add(E e)This method Appends the specified element to the end of this list.
addAll(int index, Collection c)This method Inserts all of the elements in the specified collection into this list, starting at the specified position.
addAll(Collection c)This method Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
addFirst(E e)This method Inserts the specified element at the beginning of this list.
addLast(E e)This method Appends the specified element to the end of this list.
clear()This method removes all of the elements from this list.
clone()This method returns a shallow copy of this LinkedList.
contains(Object o)This method returns true if this list contains the specified element.
descendingIterator()This method returns an iterator over the elements in this deque in reverse sequential order.
element()This method retrieves but does not remove, the head (first element) of this list.
get(int index)This method returns the element at the specified position in this list.
getFirst()This method returns the first element in this list.
getLast()This method returns the last element in this list.
indexOf(Object o)This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(Object o)This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
listIterator(int index)This method returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list.
offer(E e)This method Adds the specified element as the tail (last element) of this list.
offerFirst(E e)This method Inserts the specified element at the front of this list.
offerLast(E e)This method Inserts the specified element at the end of this list.
peek()This method retrieves but does not remove, the head (first element) of this list.
peekFirst()This method retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
peekLast()This method retrieves, but does not remove, the last element of this list, or returns null if this list is empty.
poll()This method retrieves and removes the head (first element) of this list.
pollFirst()This method retrieves and removes the first element of this list, or returns null if this list is empty.
pollLast()This method retrieves and removes the last element of this list, or returns null if this list is empty.
pop()This method Pops an element from the stack represented by this list.
push(E e)This method pushes an element onto the stack represented by this list.
remove()This method retrieves and removes the head (first element) of this list.
remove(int index)This method removes the element at the specified position in this list.
remove(Object o)This method removes the first occurrence of the specified element from this list if it is present.
removeFirst()This method removes and returns the first element from this list.
removeFirstOccurrence(Object o)This method removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
removeLast()This method removes and returns the last element from this list.
removeLastOccurrence(Object o)This method removes the last occurrence of the specified element in this list (when traversing the list from head to tail).
set(int index, E element)This method replaces the element at the specified position in this list with the specified element.
size()This method returns the number of elements in this list.
spliterator()This method creates a late-binding and fail-fast Spliterator over the elements in this list.
toArray()This method returns an array containing all of the elements in this list in proper sequence (from first to last element).
toArray(T[] a)This method returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toString()This method returns a string containing all of the elements in this list in proper sequence (from first to the last element), each element is separated by commas and the String is enclosed in square brackets.

例子:

Java
// Java Program to Demonstrate
// Implementation of LinkedList
// class
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
        // Creating object of the
        // class linked list
        LinkedList ll = new LinkedList();
 
        // Adding elements to the linked list
        ll.add("A");
        ll.add("B");
        ll.addLast("C");
        ll.addFirst("D");
        ll.add(2, "E");
 
        System.out.println(ll);
 
        ll.remove("B");
        ll.remove(3);
        ll.removeFirst();
        ll.removeLast();
 
        System.out.println(ll);
    }
}


Java
// Java program to add elements
// to a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        System.out.println(ll);
    }
}


Java
// Java program to change elements
// in a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "Geeks");
   
        System.out.println("Initial LinkedList " + ll);
   
        ll.set(1, "For");
   
        System.out.println("Updated LinkedList " + ll);
    }
}


Java
// Java program to remove elements
// in a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        System.out.println(
            "Initial LinkedList " + ll);
   
        ll.remove(1);
   
        System.out.println(
            "After the Index Removal " + ll);
   
        ll.remove("Geeks");
   
        System.out.println(
            "After the Object Removal " + ll);
    }
}


Java
// Java program to iterate the elements
// in an LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll
            = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        // Using the Get method and the
        // for loop
        for (int i = 0; i < ll.size(); i++) {
   
            System.out.print(ll.get(i) + " ");
        }
   
        System.out.println();
   
        // Using the for each loop
        for (String str : ll)
            System.out.print(str + " ");
    }
}


输出:
[D, A, E, B, C]
[A]

List-ArrayList-in-Java-In-Depth-Study

在上图中,AbstractList、CopyOnWriteArrayList 和 AbstractSequentialList 是实现列表接口的类。在每个提到的类中都实现了一个单独的功能。他们是:

  1. AbstractList:该类用于实现一个不可修改的列表,只需要扩展这个AbstractList类,实现get()和size()方法即可。
  2. CopyOnWriteArrayList:该类实现列表接口。它是 ArrayList 的增强版本,其中所有修改(添加、设置、删除等)都是通过制作列表的新副本来实现的。

对链表执行各种操作

  1. 添加元素
  2. 更新元素
  3. 移除元素
  4. 迭代元素

让我们看看如何对 LinkedList 执行一些基本操作以更好地理解它,如下所示:

操作 1:添加元素

为了向 ArrayList 添加元素,我们可以使用 add() 方法。该方法被重载以根据不同的参数执行多个操作。他们是:

  • add(Object):该方法用于在LinkedList的末尾添加一个元素。
  • add(int index, Object):此方法用于在 LinkedList 中的特定索引处添加元素。

例子:

Java

// Java program to add elements
// to a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        System.out.println(ll);
    }
}
输出:
[Geeks, For, Geeks]

操作 2:更改元素

添加元素后,如果我们希望更改元素,可以使用 set() 方法完成。由于 LinkedList 是索引的,因此我们希望更改的元素由元素的索引引用。因此,此方法采用索引和需要在该索引处插入的更新元素。

例子:

Java

// Java program to change elements
// in a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "Geeks");
   
        System.out.println("Initial LinkedList " + ll);
   
        ll.set(1, "For");
   
        System.out.println("Updated LinkedList " + ll);
    }
}
输出:
Initial LinkedList [Geeks, Geeks, Geeks]
Updated LinkedList [Geeks, For, Geeks]

操作 3:移除元素

为了从 LinkedList 中删除元素,我们可以使用 remove() 方法。该方法被重载以根据不同的参数执行多个操作。他们是:

  • remove(Object):此方法用于简单地从 LinkedList 中删除一个对象。如果有多个这样的对象,则删除第一次出现的对象。
  • remove(int index):由于 LinkedList 是索引的,因此此方法采用一个整数值,该值仅删除 LinkedList 中该特定索引处存在的元素。删除元素并更新元素的索引后,LinkedList 的对象也会更新,在删除元素后给出一个新的列表。

例子:

Java

// Java program to remove elements
// in a LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        System.out.println(
            "Initial LinkedList " + ll);
   
        ll.remove(1);
   
        System.out.println(
            "After the Index Removal " + ll);
   
        ll.remove("Geeks");
   
        System.out.println(
            "After the Object Removal " + ll);
    }
}
输出:
Initial LinkedList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]

操作4:迭代LinkedList

有多种方法可以遍历 LinkedList。最著名的方法是结合使用基本的 for 循环和 get() 方法来获取特定索引处的元素和高级 for 循环。

例子:

Java

// Java program to iterate the elements
// in an LinkedList
   
import java.util.*;
   
public class GFG {
   
    public static void main(String args[])
    {
        LinkedList ll
            = new LinkedList<>();
   
        ll.add("Geeks");
        ll.add("Geeks");
        ll.add(1, "For");
   
        // Using the Get method and the
        // for loop
        for (int i = 0; i < ll.size(); i++) {
   
            System.out.print(ll.get(i) + " ");
        }
   
        System.out.println();
   
        // Using the for each loop
        for (String str : ll)
            System.out.print(str + " ");
    }
}
输出:
Geeks For Geeks 
Geeks For Geeks