2022년 03월 07일 월요일 - 월요일이 시작됐다....................


오늘 올려볼 문제는 21번 Merge Two Sorted Lists 이라는 문제이다.


사진을 클릭하면 해당 문제로 이동합니다.

leetcode 문제 사진

오늘도 LeetCode 사이트 오늘의 문제를 가지고 왔다.

쓸게 좀 있어서 3분컷!


입력


사진에서도 볼 수 있듯이 정렬된 LinkedList 2개가 입력으로 들어온다.



풀이 및 코드


LinkedList 2개를 merge 하여 리턴하는 문제다.


오늘은 처음부터 정답을 생각해냈다.

그냥 직관대로 풀면된다.


이제 코드를 봐보자!


풀이코드

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode();
        ListNode now = result;
        while(list1 != null && list2 != null)
        {
            if(list1.val > list2.val)
            {
                now.next = list2;
                list2 = list2.next;
            }
            else
            {
                now.next = list1;
                list1 = list1.next;
            }
            now = now.next;
        }

        while(list1 != null)
        {
            now.next = list1;
            list1 = list1.next;
            now = now.next;
        }

        while(list2 != null)
        {
            now.next = list2;
            list2 = list2.next;
            now = now.next;
        }

        return result.next;
    }
}




제출 화면

leetcode 문제 맞았습니다


오늘은 문제가 너무 쉬웠다.

내일은 재밌는 적당히 어려운 문제가 나왔으면 좋겠다.


내일도 문제를 풀어서 블로그에 글을 쓸 수 있으면 좋겠다.

+ Recent posts