상세 컨텐츠

본문 제목

[LeetCode] 21. Merge Two Sorted List

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2024. 11. 20. 19:35

본문

       문제 요약        

- 문제

ListNode 2개를 하나로 합치는 작업

 

 

         아이디어        

두 개를 비교하면서 작은 값 먼저 ans.next에 붙이기

처음에 ListNode res = new ListNode(-1);를 설정

포인터를 잃어버리므로 ListNode ans = res; 로 복사해둠

 

 

         소스코드        

/**
 * 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 res = new ListNode(-1);
        ListNode ans = res;
        while(list1 != null && list2 != null){
            if(list1.val <= list2.val){
                ans.next = list1;
                list1 = list1.next;
                ans = ans.next;
            }else{
                ans.next = list2;
                list2 = list2.next;
                ans = ans.next;
            }
        }
        while(list1 != null){
            ans.next = list1;
            list1 = list1.next;
            ans = ans.next;
        }
        while(list2 != null){
            ans.next = list2;
            list2 = list2.next;
            ans = ans.next;
        }
        return res.next;
    }
}

 

 

728x90

'💯ProblemSolving > 문제 풀이-Java' 카테고리의 다른 글

[BJ] 15553 : 난로  (0) 2024.11.22
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree  (0) 2024.11.22
[BJ] 1922 : 네트워크 연결  (0) 2024.11.20
[SWEA] 미생물격리  (0) 2024.11.16
[BJ] 2251 : 물통  (0) 2024.11.15

관련글 더보기