Linked List List_1과 List_2라는 두 가지 데이터 구조가 제공됩니다. 작업은 연결 목록 'List_2'의 요소를 다른 위치의 연결 목록 'List_1'에 병합하는 것이며, 'List_1'에 병합할 수 없는 요소가 남아 있으면 ' List_2' 나머지 요소.
예:
에서 -
목록_1 =

목록_2 =

밖으로 − 병합된 목록은-:

설명 - List_1과 List_2라는 두 개의 목록이 제공됩니다. list_2의 가능한 요소를 다른 위치의 List_1에 병합했습니다. 따라서 List_1에서 병합 후 요소는 10->3->2->1->1->4->2->5->5이고 List_2는 7->2입니다.
에서 -
목록_1 =11 -> 12 -> 13
목록_2 =14 -> 15 -> 16 -> 17 -> 18
밖으로 −병합 목록은 -:11 -> 14 -> 12 -> 15 -> 13
입니다.설명 −우리는 List_1과 List_2라는 두 개의 목록이 제공됩니다. list_2의 가능한 요소를 다른 위치의 List_1에 병합했습니다. 따라서 List_1에서 병합 후 요소는 11 -> 14 -> 12 -> 15 -> 13이고 List_2에서는 16->17->18입니다.
아래 프로그램에서 사용된 접근 방식은 다음과 같습니다 -
-
연결 목록의 첫 번째 노드를 가리키는 헤드 노드를 만듭니다.
-
Node의 클래스를 생성하여 값과 next를 데이터 멤버로 가지는 연결 목록을 생성합니다. 기본 생성자를 Node(int val)로 정의하고 값을 val로, next를 NULL로 설정합니다.
-
연결 목록에 요소를 추가하는 add(int updated_value) 메서드 내부.
-
new_node로 개체를 만들고 updated_value를 기본 생성자에 전달합니다.
-
new_node.next를 헤드로 설정하고 헤드를 new_node로 설정
-
-
mergeList(TutorialPoint list)
의 함수 내부-
객체를 n1_curr로 생성하고 head로 설정하고 n2_curr을 list.head로 설정
-
n1_next 및 n2_next
로 개체 생성 -
동안 n1_curr !=null AND n2_curr !=null로 시작합니다. 동안 n1_next는 n1_curr.next, n2_next는 n2_curr.next, n2_curr.next는 n1_next, n1_curr.next는 n2_curr, n1_curr은 n1_next, n2_curr은 n2_입니다.
-
list.head를 n2_curr로 설정
-
-
main() 메소드 내부
-
개체를 TutorialPoint list_1에서 new TutorialPoint()로, TutorialPoint list_2에서 new TutorialPoint()로 개체를 만듭니다.
-
list_1에 요소를 list_1.add(13), list_1.add(12) 및 list_1.add(11)로 추가합니다.
-
list_2에 요소를 list_2.add(18), list_2.add(17), list_2.add(16), list_2.add(15) 및 list_2.add(14)로 추가
-
mergeList 메소드를 호출하여 list_2의 요소를 list_1에 list_1.mergeList(list_2)
로 병합합니다. -
최종 목록을 출력으로 인쇄합니다.
-
예시
public class TutorialPoint{
Node head;
class Node{
int value;
Node next;
Node(int val){
value = val;
next = null;
}
}
void add(int updated_value){
Node new_node = new Node(updated_value);
new_node.next = head;
head = new_node;
}
void mergeList(TutorialPoint list){
Node n1_curr = head, n2_curr = list.head;
Node n1_next, n2_next;
while (n1_curr != null && n2_curr != null){
n1_next = n1_curr.next;
n2_next = n2_curr.next;
n2_curr.next = n1_next;
n1_curr.next = n2_curr;
n1_curr = n1_next;
n2_curr = n2_next;
}
list.head = n2_curr;
}
public static void main(String args[]){
TutorialPoint list_1 = new TutorialPoint();
TutorialPoint list_2 = new TutorialPoint();
list_1.add(13);
list_1.add(12);
list_1.add(11);
list_2.add(18);
list_2.add(17);
list_2.add(16);
list_2.add(15);
list_2.add(14);
list_1.mergeList(list_2);
System.out.println("Merged list is:");
Node temp = list_1.head;
while (temp != null){
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}
} 출력
위의 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Merged list is: 11 14 12 15 13 16