在此示例中,我們將學習在Java中的一次迭代中獲取鏈表的中間元素。
要了解此示例,請確保您首先訪問以下教程,
class LinkedList {
//創(chuàng)建Node類的對象
//表示鏈表的頭部
Node head;
//靜態(tài)內(nèi)部類
static class Node {
int value;
//將每個節(jié)點連接到下一個節(jié)點
Node next;
Node(int d) {
value = d;
next = null;
}
}
public static void main(String[] args) {
//創(chuàng)建一個LinkedList對象
LinkedList linkedList = new LinkedList();
//為每個鏈表節(jié)點賦值
linkedList.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
//將鏈表中的每個節(jié)點連接到下一個節(jié)點
linkedList.head.next = second;
second.next = third;
//打印鏈表
Node pointer = linkedList.head;
System.out.print("LinkedList: " );
while (pointer != null) {
System.out.print(pointer.value + " ");
pointer = pointer.next;
}
// 找到中間元素
Node ptr1 = linkedList.head;
Node ptr2 = linkedList.head;
while (ptr1.next != null) {
//將ptr1增加2,將ptr2增加1
//如果ptr1指向最后一個元素
//ptr2將指向中間元素
ptr1 = ptr1.next;
if(ptr1.next !=null) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
}
System.out.println("\n中間元素: " + ptr2.value);
}
}輸出結果
LinkedList: 1 2 3 中間元素: 2
在上面的示例中,我們已經(jīng)用Java實現(xiàn)了鏈表數(shù)據(jù)結構。然后,我們在一個循環(huán)中找到鏈表的中間元素。注意代碼,
while (ptr1.next != null) {
//將ptr1增加2,將ptr2增加1
//如果ptr1指向最后一個元素
//ptr2將指向中間元素
ptr1 = ptr1.next;
if(ptr1.next !=null) {
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
}在這里,我們有兩個變量ptr1和ptr2。 我們使用這些變量來遍歷鏈表。
在每次迭代中,ptr1將訪問兩個節(jié)點,而ptr2將訪問鏈表的單個節(jié)點。
現(xiàn)在,當ptr1到達鏈接列表的末尾時,ptr2將位于中間。 這樣,我們可以在單次迭代中獲得鏈表的中間位置。
import java.util.LinkedList;
class Main {
public static void main(String[] args){
//使用 LinkedList 類創(chuàng)建鏈表
LinkedList<String> animals = new LinkedList<>();
//向 LinkedList 添加元素
animals.add("Dog");
animals.addFirst("Cat");
animals.addLast("Horse");
System.out.println("LinkedList: " + animals);
//訪問中間元素
String middle = animals.get(animals.size()/2);
System.out.println("中間元素: " + middle);
}
}輸出結果
LinkedList: [Cat, Dog, Horse] 中間元素: Dog
在上面的示例中,我們使用了LinkedList類來實現(xiàn)鏈表數(shù)據(jù)結構。注意表達式
animals.get(animals.size()/2)
size()/ 2 - 返回中間元素的位置
get() - 返回位于中間位置的元素