Java LinkedList (z przykładami)

W tym samouczku szczegółowo poznamy bibliotekę Java LinkedList na przykładach.

LinkedListKlasa zbiorów ramach Java dostarcza funkcjonalności połączonej struktury danych (lista podwójnie LinkedList).

Java Double LinkedList

Każdy element na połączonej liście jest nazywany węzłem . Składa się z 3 pól:

  • Prev - przechowuje adres poprzedniego elementu na liście. Dotyczy nullpierwszego elementu
  • Dalej - przechowuje adres kolejnego elementu na liście. To nullostatni element
  • Dane - przechowuje aktualne dane

Tworzenie Java LinkedList

Oto jak możemy tworzyć połączone listy w Javie:

 LinkedList linkedList = new LinkedList();

Tutaj Type wskazuje typ połączonej listy. Na przykład,

 // create Integer type linked list LinkedList linkedList = new LinkedList(); // create String type linked list LinkedList linkedList = new LinkedList();

Przykład: Utwórz LinkedList w Javie

 import java.util.LinkedList; class Main ( public static void main(String() args)( // create linkedlist LinkedList animals = new LinkedList(); // Add elements to LinkedList animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); System.out.println("LinkedList: " + animals); ) )

Wynik

 LinkedList: (Pies, Kot, Krowa)

W powyższym przykładzie utworzyliśmy LinkedListnazwane zwierzęta.

Tutaj użyliśmy add()metody, aby dodać elementy do LinkedList. Dowiemy się więcej o tej add()metodzie w dalszej części tego samouczka.

Praca z Java LinkedList

Elementy na połączonych listach nie są przechowywane w kolejności. Zamiast tego są rozproszone i połączone za pomocą linków ( poprzednia i następna ).

Implementacja Java LinkedList

Tutaj mamy 3 elementy na połączonej liście.

  • Pies - jest to pierwszy element, który ma wartość null jako poprzedni adres, a adres Cat jako następny adres
  • Kot - to drugi element, który zawiera adres Psa jako poprzedni, a adres Krowy jako następny
  • Krowa - jest to ostatni element, który przechowuje adres Cat jako poprzedni adres i null jako następny element

Aby dowiedzieć się więcej, odwiedź strukturę danych LinkedList.

Metody Java LinkedList

LinkedListudostępnia różne metody, które pozwalają nam wykonywać różne operacje na połączonych listach. W tym samouczku przyjrzymy się czterem powszechnie używanym operatorom LinkedList:

  • Dodaj elementy
  • Dostęp do elementów
  • Zmień elementy
  • Usuń elementy

1. Dodaj elementy do LinkedList

Możemy użyć tej add()metody, aby dodać element (węzeł) na końcu LinkedList. Na przykład,

 import java.util.LinkedList; class Main ( public static void main(String() args)( // create linkedlist LinkedList animals = new LinkedList(); // add() method without the index parameter animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); System.out.println("LinkedList: " + animals); // add() method with the index parameter animals.add(1, "Horse"); System.out.println("Updated LinkedList: " + animals); ) )

Wynik

 LinkedList: (Pies, Kot, Krowa) Zaktualizowany LinkedList: (Pies, Koń, Kot, Krowa)

W powyższym przykładzie utworzyliśmy LinkedList o nazwie zwierzęta. Tutaj zastosowaliśmy add()metodę dodawania elementów do zwierząt.

Zwróć uwagę na oświadczenie,

 animals.add(1, "Horse");

Tutaj użyliśmy parametru numeru indeksu . Jest to opcjonalny parametr określający pozycję, w której zostanie dodany nowy element.

Aby dowiedzieć się więcej o dodawaniu elementów do LinkedList, odwiedź program Java, aby dodać elementy do LinkedList.

2. Uzyskaj dostęp do elementów LinkedList

get()Metodą klasy LinkedList służy do łączenia elementu z LinkedList. Na przykład,

 import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in the linked list languages.add("Python"); languages.add("Java"); languages.add("JavaScript"); System.out.println("LinkedList: " + languages); // get the element from the linked list String str = languages.get(1); System.out.print("Element at index 1: " + str); ) )

Wynik

 LinkedList: (Python, Java, JavaScript) Element w indeksie 1: Java

W powyższym przykładzie użyliśmy get()metody z parametrem 1 . Tutaj metoda zwraca element o indeksie 1 .

Możemy również elementy dostępowe do LinkedList użyciu iterator(), a listIterator()metody. Aby dowiedzieć się więcej, odwiedź program Java, aby uzyskać dostęp do elementów LinkedList.

3. Zmień elementy LinkedList

set()Metoda LinkedListklasy służy do zmiany elementów LinkedList. Na przykład,

 import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in the linked list languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); languages.add("Java"); System.out.println("LinkedList: " + languages); // change elements at index 3 languages.set(3, "Kotlin"); System.out.println("Updated LinkedList: " + languages); ) )

Wynik

 LinkedList: (Java, Python, JavaScript, Java) Zaktualizowany LinkedList: (Java, Python, JavaScript, Kotlin)

W powyższym przykładzie utworzyliśmy LinkedList o nazwanych językach. Zwróć uwagę na linię,

 languages.set(3, "Kotlin");

Tutaj set()metoda zmienia element o indeksie 3 na Kotlin.

4. Usuń element z LinkedList

The remove() method of the LinkedList class is used to remove an element from the LinkedList. For example,

 import java.util.LinkedList; class Main ( public static void main(String() args) ( LinkedList languages = new LinkedList(); // add elements in LinkedList languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); languages.add("Kotlin"); System.out.println("LinkedList: " + languages); // remove elements from index 1 String str = languages.remove(1); System.out.println("Removed Element: " + str); System.out.println("Updated LinkedList: " + languages); ) )

Output

 LinkedList: (Java, Python, JavaScript, Kotlin) Removed Element: Python New LinkedList: (Java, JavaScript, Kotlin)

Here, the remove() method takes the index number as the parameter. And, removes the element specified by the index number.

To learn more about removing elements from the linkedlist, visit the Java program to remove elements from LinkedList…

Other Methods

Methods Description
contains() checks if the LinkedList contains the element
indexOf() returns the index of the first occurrence of the element
lastIndexOf() returns the index of the last occurrence of the element
clear() removes all the elements of the LinkedList
iterator() returns an iterator to iterate over LinkedList

LinkedList as Deque and Queue

Since the LinkedList class also implements the Queue and the Deque interface, it can implement methods of these interfaces as well. Here are some of the commonly used methods:

Methods Descriptions
addFirst() adds the specified element at the beginning of the linked list
addLast() adds the specified element at the end of the linked list
getFirst() returns the first element
getLast() returns the last element
removeFirst() removes the first element
removeLast() removes the last element
peek() returns the first element (head) of the linked list
poll() returns and removes the first element from the linked list
offer() adds the specified element at the end of the linked list

Example: Java LinkedList as Queue

 import java.util.LinkedList; import java.util.Queue; class Main ( public static void main(String() args) ( Queue languages = new LinkedList(); // add elements languages.add("Python"); languages.add("Java"); languages.add("C"); System.out.println("LinkedList: " + languages); // access the first element String str1 = languages.peek(); System.out.println("Accessed Element: " + str1); // access and remove the first element String str2 = languages.poll(); System.out.println("Removed Element: " + str2); System.out.println("LinkedList after poll(): " + languages); // add element at the end languages.offer("Swift"); System.out.println("LinkedList after offer(): " + languages); ) )

Output

 LinkedList: (Python, Java, C) Accessed Element: Python Removed Element: Python LinkedList after poll(): (Java, C) LinkedList after offer(): (Java, C, Swift)

Example: LinkedList as Deque

 import java.util.LinkedList; import java.util.Deque; class Main ( public static void main(String() args)( Deque animals = new LinkedList(); // add element at the beginning animals.add("Cow"); System.out.println("LinkedList: " + animals); animals.addFirst("Dog"); System.out.println("LinkedList after addFirst(): " + animals); // add elements at the end animals.addLast("Zebra"); System.out.println("LinkedList after addLast(): " + animals); // remove the first element animals.removeFirst(); System.out.println("LinkedList after removeFirst(): " + animals); // remove the last element animals.removeLast(); System.out.println("LinkedList after removeLast(): " + animals); ) )

Output

 LinkedList: (Cow) LinkedList after addFirst(): (Dog, Cow) LinkedList after addLast(): (Dog, Cow, Zebra) LinkedList after removeFirst(): (Cow, Zebra) LinkedList after removeLast(): (Cow)

Iterating through LinkedList

We can use the Java for-each loop to iterate through LinkedList. For example,

 import java.util.LinkedList; class Main ( public static void main(String() args) ( // Creating a linked list LinkedList animals = new LinkedList(); animals.add("Cow"); animals.add("Cat"); animals.add("Dog"); System.out.println("LinkedList: " + animals); // Using forEach loop System.out.println("Accessing linked list elements:"); for(String animal: animals) ( System.out.print(animal); System.out.print(", "); ) ) )

Output

 LinkedList: (Cow, Cat, Dog) Accessing linked list elements: Cow, Cat, Dog,

LinkedList Vs. ArrayList

Both the Java ArrayList and LinkedList implements the List interface of the Collections framework. However, there exists some difference between them.

LinkedList ArrayList
Implements List, Queue, and Deque interfaces. Implements List interface.
Stores 3 values (previous address, data, and next address) in a single position. Przechowuje pojedynczą wartość w jednej pozycji.
Zapewnia podwójnie połączoną implementację listy. Zapewnia implementację tablicy o zmiennym rozmiarze.
Za każdym razem, gdy dodaje się element previ nextzmienia się adres. Za każdym razem, gdy dodawany jest element, wszystkie elementy po tej pozycji są przesuwane.
Aby uzyskać dostęp do elementu, musimy iterować od początku do elementu. Może losowo uzyskiwać dostęp do elementów za pomocą indeksów.

Uwaga : możemy również utworzyć LinkedList przy użyciu interfejsów w Javie. Na przykład,

 // create linkedlist using List List animals1 = new LinkedList(); // creating linkedlist using Queue Queue animals2 = new LinkedList(); // creating linkedlist using Deque Deque animals3 = new LinkedList();

Tutaj, jeśli LinkedList jest tworzony przy użyciu jednego interfejsu, nie możemy użyć metod dostarczonych przez inne interfejsy. Oznacza to, że zwierzęta1 nie mogą używać metod specyficznych dla interfejsów Queuei Deque.

Interesujące artykuły...