문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
당신은 두 개의 정렬된 연결리스트 list1과 list2의 헤드를 가지게 된다.
두 개의 리스트를 하나의 정렬된 리스트로 합쳐라. 그 리스트는 두 목록의 노드를 연결하여 만들어야 한다.
합쳐진 연결 리스트의 헤더를 반환해라.
#1
Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 1, 2, 3, 4, 4]
#2
Input: list1 = [], list2 = []
Output: []
#3
Input: list1 = [], list2 = [0]
Output: [0]
문제에 주석으로 주어진 ListNode를 사용해서 문제를 풀어야 한다.
임시로 사용할 ListNode tempNode를 생성하고, 현재 Node를 담아둘 currNode에 생성한 tempNode를 할당한다.
ListNode tempNode = new ListNode(-101);
ListNode currNode = tempNode;
while문을 통해 list1과 list2가 null이 될 때까지 반복한다.
list1과 list2의 각각 val을 비교하여, val이 작은 리스트를 currNode의 next에 할당하고, 해당 리스트에 리스트의 next를 할당한다.
if문을 빠져나왔다면 currNode에 currNode의 next를 할당한다.
while(list1 != null && list2 != null){
if(list1.val < list2.val){
currNode.next = list1;
list1 = list1.next;
}else{
currNode.next = list2;
list2 = list2.next;
}
currNode = currNode.next;
}
while문을 빠져나왔다면, list1과 list2를 각각 null인지 확인하고, list1이 null이면 currNode.next에 list2를 할당한다.
list2가 null이면 currNode.next에 list1을 할당한다.
if(list1 == null){
currNode.next = list2;
}
if(list2 == null){
currNode.next = list1;
}
마지막엔 tempNode.next를 반환해라.
return tempNode.next;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode tempNode = new ListNode(-101);
ListNode currNode = tempNode;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
currNode.next = list1;
list1 = list1.next;
}else{
currNode.next = list2;
list2 = list2.next;
}
currNode = currNode.next;
}
if(list1 == null){
currNode.next = list2;
}
if(list2 == null){
currNode.next = list1;
}
return tempNode.next;
}
}