[LeetCode] Merge Two Sorted Lists

아르당·2024년 11월 21일

LeetCode

목록 보기
7/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

당신은 두 개의 정렬된 연결리스트 list1과 list2의 헤드를 가지게 된다.
두 개의 리스트를 하나의 정렬된 리스트로 합쳐라. 그 리스트는 두 목록의 노드를 연결하여 만들어야 한다.
합쳐진 연결 리스트의 헤더를 반환해라.

Example

#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]

Constraints

  • 두 리스트의 노드 수는 [0, 50] 범위 안에 있다.
  • -100 <= Node.val <= 100
  • list1과 list2 둘 다 오름차순으로 정렬되어 있다.

Solved

문제에 주석으로 주어진 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;

All Code

/**
 * 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;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글