이 기사에서는 한 번의 반복으로 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