이 글에서는 자바(Java)에서 연결 리스트(LinkedList)에 요소를 추가하는 방법을 알아보겠습니다.
java.util.LinkedList 클래스는 이중 연결 리스트(doubly-linked list)에서 기대할 수 있는 모든 연산을 수행합니다. 인덱스를 사용하는 연산이 실행될 때는 지정된 인덱스에 더 가까운 쪽, 즉 리스트의 시작 또는 끝 중 어느 쪽이 가까운지에 따라 해당 방향부터 탐색을 진행합니다.
동작 원리
프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
입력 −
Run the program
출력 −
The elements added to the lists are: [Java, Python, Scala, Shell]
알고리즘
Step 1 - START Step 2 - Declare a linkedlist namely input_list Step 3 – Using the built-in function add(), we add the elements to the list Step 4 - Display the result Step 5 - Stop
예제 1: 리스트 끝에 요소 추가하기
첫 번째 예제에서는 add() 메서드를 사용하여 리스트의 맨 뒤에 요소를 하나씩 추가합니다. add() 메서드는 별도의 위치 지정 없이 호출하면 항상 리스트의 마지막에 새 요소를 삽입합니다.
import java.util.LinkedList;
public class Demo {
public static void main(String[] args){
LinkedList<String> input_list = new LinkedList<>();
System.out.println("A list is declared");
input_list.add("Java");
input_list.add("Python");
input_list.add("Scala");
input_list.add("Shell");
System.out.println("The elements added to the lists are: " + input_list);
}
}
출력 결과
A list is declared The elements added to the lists are: [Java, Python, Scala, Shell]
예제 2: 특정 위치에 요소 추가하기
두 번째 예제에서는 인덱스를 지정하여 리스트의 원하는 위치에 요소를 삽입합니다. add(index, element) 형태로 호출하면 해당 인덱스 위치에 요소가 삽입되고, 기존 요소들은 자동으로 한 칸씩 뒤로 밀려납니다.
import java.util.LinkedList;
public class Demo {
public static void main(String[] args){
LinkedList<String> input_list = new LinkedList<>();
input_list.add("Java");
input_list.add("Python");
input_list.add("JavaScript");
System.out.println("The list is defined as: " + input_list);
input_list.add(1, "Scala");
System.out.println("The list after adding element at position 1: " + input_list);
}
}
출력 결과
The list is defined as: [Java, Python, JavaScript] The list after adding element at position 1: [Java, Scala, Python, JavaScript]
마무리
LinkedList 클래스의 add() 메서드는 매개변수 개수에 따라 동작이 달라집니다. 요소만 전달하면 리스트 맨 뒤에 추가되고, 인덱스와 요소를 함께 전달하면 해당 위치에 삽입됩니다. 이중 연결 리스트 구조 덕분에 양방향 삽입과 삭제가 효율적으로 처리되므로, 빈번한 삽입·삭제 연산이 필요한 경우 ArrayList 대신 LinkedList를 활용하는 것이 좋습니다.