PS

Leetcode 21. Merge Two Sorted Lists

Bryan Lee 2022. 4. 26. 14:11

문제 이해

- 두 정렬된 링크드 리스트를 합쳐라 

 

해결 전략

- 링크드 리스트의 기본 문제입니다. 

- ListNode dummy와 head를 선언한 후,  

  head에 조건에 맞게 값들을 추가합니다.

- 마지막으로 dummy.next를 반환합니다. 

 

구현

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        
        ListNode dummy = new ListNode(0);
        ListNode head = dummy; 
        
        while(list1 != null && list2 != null){
        
            if(list1.val < list2.val){
                head.next = new ListNode(list1.val);
                head = head.next;
                list1 = list1.next;
            }else{
                head.next = new ListNode(list2.val);
                head = head.next;
                list2 = list2.next;
            }
        }
        
        while(list1 != null){
            head.next = new ListNode(list1.val);
            head = head.next;
            list1 = list1.next;
        }
        
        while(list2 != null){
            head.next = new ListNode(list2.val);
            head = head.next;
            list2 = list2.next;
        }
        
        return dummy.next;
        
        
    }
}

피드백

- list1과 list2에서 값으로 새로운 노드를 만들었으면,

  list1 = list1.next, list2 = list2.next로 이동해야 합니다. 

'PS' 카테고리의 다른 글

Leetcode 1. Two sum  (0) 2022.05.03
Leetcode 2. Add Two Numbers  (0) 2022.04.30
Leetcode 234. Palindrome Linked List  (2) 2022.04.26
Leetcode 203. Remove Linked List Elements  (1) 2022.04.26
Leetcode 876. Middle of the Linked List  (0) 2022.04.25