用单次迭代获取链表中间元素的 Java 程序
在本文中,我们将了解如何通过单次迭代获得 LinkedList 的中间元素。 java.util.LinkedList 类操作执行我们对双向链表所期望的操作。对列表进行索引的操作将从开头或结尾遍历列表,以距离指定索引更近的方式进行。
下面是相同的演示 −
假设我们的输入是 −
Input linked list: 100 200 330
期望的输出将是 −
The middle element of the list is: 200
算法
Step 1 - START Step 2 - Declare a LinkedList namely input_list. Declare five node objects namely head, first_node, second_node, pointer_1, pointer_2. Step 3 - Define the values. Step 4 - Using a while loop, iterate over the linked list, get the middle element by traversing the list using pointer_1 and pointer_2 until pointer_1.next is not null. Step 5 - Display the pointer_2 value as result. Step 6 - Stop
示例 1
在这里,我们在“main”函数下绑定所有操作。
public class LinkedList { Node head; static class Node { int value; Node next; Node(int d) { value = d; next = null; } } public static void main(String[] args) { LinkedList input_list = new LinkedList(); input_list.head = new Node(100); Node second_node = new Node(200); Node third_node = new Node(330); input_list.head.next = second_node; second_node.next = third_node; Node current_node = input_list.head; System.out.print("The linked list is defined as: " ); while (current_node != null) { System.out.print(current_node.value + " "); current_node = current_node.next; } Node pointer_1 = input_list.head; Node pointer_2 = input_list.head; while (pointer_1.next != null) { pointer_1 = pointer_1.next; if(pointer_1.next !=null) { pointer_1 = pointer_1.next; pointer_2 = pointer_2.next; } } System.out.println("\nThe middle element of the list is: " + pointer_2.value); } }
输出
The linked list is defined as: 100 200 330 The middle element of the list is: 200
示例 2
在这里,我们将操作封装到展示面向对象编程的函数中。
public class LinkedList { Node head; static class Node { int value; Node next; Node(int d) { value = d; next = null; } } static void get_middle_item(LinkedList input_list){ Node pointer_1 = input_list.head; Node pointer_2 = input_list.head; while (pointer_1.next != null) { pointer_1 = pointer_1.next; if(pointer_1.next !=null) { pointer_1 = pointer_1.next; pointer_2 = pointer_2.next; } } System.out.println("\nThe middle element of the list is: " + pointer_2.value); } public static void main(String[] args) { LinkedList input_list = new LinkedList(); input_list.head = new Node(100); Node second_node = new Node(200); Node third_node = new Node(330); input_list.head.next = second_node; second_node.next = third_node; Node current_node = input_list.head; System.out.print("The linked list is defined as: " ); while (current_node != null) { System.out.print(current_node.value + " "); current_node = current_node.next; } get_middle_item(input_list); } }
输出
The linked list is defined as: 100 200 330 The middle element of the list is: 200
广告