Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java LinkedList에서 요소를 제거하는 방법 – 예제 코드로 배우기

이 글에서는 자바(Java)의 LinkedList에서 요소를 제거하는 방법을 예제 코드와 함께 살펴봅니다.

LinkedList 클래스 개요

java.util.LinkedList 클래스는 이중 연결 리스트(doubly-linked list)에서 기대할 수 있는 모든 연산을 수행할 수 있습니다. 인덱스를 사용해 목록에 접근하는 연산은 지정된 인덱스에 더 가까운 쪽, 즉 목록의 처음 또는 끝 중 어느 쪽이 가까운지에 따라 순회 방향을 결정합니다. 덕분에 양방향 탐색이 가능해 성능 면에서 유리합니다.

요소를 제거할 때 사용하는 remove() 메서드는 매개변수 없이 호출하면 목록의 첫 번째 요소(head)를 반환하면서 삭제합니다.

아래는 실제 동작 과정을 시연한 예시입니다.

입력값:

The list is defined as: [Java, Scala, Python, JavaScript, C++]

기대 출력값:

The list after removing all the elements is: [Python, JavaScript, C++]

알고리즘

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Display the result
Step 5 - Stop

예제 1 – main 함수에서 직접 처리

첫 번째 예제는 모든 연산을 main 함수 안에서 한 번에 처리하는 방식입니다. add() 메서드로 요소를 추가한 뒤, remove()를 두 번 호출하여 앞의 두 요소('Java', 'Scala')를 차례로 삭제합니다.

import java.util.LinkedList;
public class Demo {
    public static void main(String args[]){
        LinkedList<String> input_list = new LinkedList<String>();
        input_list.add("Java");
        input_list.add("Scala");
        input_list.add("Python");
        input_list.add("JavaScript");
        input_list.add("C++");
        System.out.println("The list is defined as: " + input_list);
        input_list.remove();
        input_list.remove();
        System.out.println("The list after removing all the elements is: " + input_list);
    }
}

실행 결과

The list is defined as: [Java, Scala, Python, JavaScript, C++]
The list after removing all the elements is: [Python, JavaScript, C++]

예제 2 – 별도의 함수로 분리 (객체 지향 방식)

두 번째 예제는 코드 재사용성과 가독성을 높이기 위해 요소 삭제 로직을 별도의 함수로 캡슐화했습니다. 이는 객체 지향 프로그래밍(OOP) 원칙에 더 부합하는 구조입니다.

import java.util.LinkedList;
public class Demo {
    static void remove_element(LinkedList<String> input_list){
        input_list.remove();
        input_list.remove();
        System.out.println("The list after removing all the elements is: " + input_list);
    }
    public static void main(String args[]){
        LinkedList<String> input_list = new LinkedList<String>();
        input_list.add("Java");
        input_list.add("Scala");
        input_list.add("Python");
        input_list.add("JavaScript");
        input_list.add("C++");
        System.out.println("The list is defined as: " + input_list);
        remove_element(input_list);
    }
}

실행 결과

The list is defined as: [Java, Scala, Python, JavaScript, C++]
The list after removing all the elements is: [Python, JavaScript, C++]

정리

두 예제 모두 remove() 메서드를 활용해 LinkedList의 앞부분 요소를 순차적으로 제거하는 방식을 보여줍니다. 단순히 첫 요소만 삭제하려면 remove(), 특정 위치의 요소를 삭제하려면 remove(int index), 특정 값을 삭제하려면 remove(Object o)를 사용하면 됩니다. 상황에 맞는 메서드를 선택하면 더욱 효율적인 리스트 관리가 가능합니다.