English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste exemplo, vamos aprender a obter o elemento médio da lista encadeada em uma iteração no Java.
Para entender este exemplo, certifique-se de que você primeiro visite o seguinte tutorial:
class LinkedList { //Crie um objeto da classe Node //Representa a cabeça da lista Node head; //Classe interna estática static class Node { int value; //Conecte cada nó ao nó seguinte Node next; Node(int d) { value = d; next = null; } } public static void main(String[] args) { //创建一个 LinkedList 对象 LinkedList linkedList = new LinkedList(); //为每个链表节点赋值 linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); //将链表中的每个节点连接到下一个节点 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); } }
Output result
LinkedList: 1 2 3 中间元素: 2
在上面的示例中,我们已经用 Java 实现了链表数据结构。然后,我们在一个循环中找到链表的中间元素。注意代码,
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将访问两个节点,而 ptr2将访问链表的单个节点。
现在,当 ptr1到达链接列表的末尾时,ptr2位于中间。这样,我们可以在单次迭代中获得链表的中间位置。
import java.util.LinkedList; class Main { public static void main(String[] args){ //使用 LinkedList 类创建链表 LinkedList<String> animals = new LinkedList<>(); //Add elements to LinkedList animals.add("Dog"); animals.addFirst("Cat"); animals.addLast("Horse"); System.out.println("LinkedList: " + animals); //Access the middle element String middle = animals.get(animals.size())/2); System.out.println("Middle element: " + middle); } }
Output result
LinkedList: [Cat, Dog, Horse] Middle element: Dog
In the above example, we used the LinkedList class to implement the linked list data structure. Note the expression
animals.get(animals.size())/2)
size()/ 2 - Return the position of the middle element
get() - Return the element in the middle position