코딩테스트

21. Merge Two Sorted Lists

nayoon 2024. 1. 29. 18:29

https://jaime-note.tistory.com/262

머리가 나빠서 node와 node를 연결하지 못하고 있다.

 

풀이 중

/**
 * 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; }
 * }
 */

 /*
    1. 문제 해석하기
    정렬된 링크드 리스트가 list1, list2가 주어지고 이 리스트를 합쳐서 정렬된 형태의 리스트로 반환해줍니다.

    2. 문제 풀이 방향
    list1과 list2의 노드를 각각 비교하면서 새로운 리스트를 만들면 될 것 같습니다.

    이때, 각 node는 val을 가지고 새롭게 선언해서 next
  */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode();
        ListNode root = new ListNode();

        ListNode temp;
        while(true) {
            if (list1 == null || list2 == null) {
                break;
            }
            if (list1.val >= list2.val) {
                temp = new ListNode(list2.val);
                list2 = list2.next;
            } else {
                temp = new ListNode(list1.val);
                list1 = list1.next;
            }
            
            temp.next = result.next;
            result.next = temp;
            System.out.println(result.next.val);
        }
        
        if (list1 == null) {
            result.next = list2;
        } else {
            result.next = list1;
        }
        return result;
    }
}

 

참고한 풀이

 

/**
 * 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; }
 * }
 */

 /*
    1. 문제 해석하기
    정렬된 링크드 리스트가 list1, list2가 주어지고 이 리스트를 합쳐서 정렬된 형태의 리스트로 반환해줍니다.

    2. 문제 풀이 방향
    list1과 list2의 노드를 각각 비교하면서 새로운 리스트를 만들면 될 것 같습니다.

    이때, 각 node는 val을 가지고 새롭게 선언해서 next
  */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode(0); // 시작점
        ListNode head = result; // 노드를 이어나갈 포인터 역할

        while(list1 != null && list2 != null) {
            if (list1.val >= list2.val) {
                head.next = list2;
                list2 = list2.next;
            } else {
                head.next = list1;
                list1 = list1.next;
            }
            
            head = head.next;
        }
        
        if (list1 == null) {
            head.next = list2;
        } else {
            head.next = list1;
        }

        return result.next;
    }
}

'코딩테스트' 카테고리의 다른 글

206. Reverse Linked List  (0) 2024.02.04
141. Linked List Cycle  (0) 2024.01.29
235. Lowest Common Ancestor of a Binary Search Tree  (0) 2024.01.28
Valid Palindrome  (0) 2024.01.18
[leetcode] 46. Permutations  (0) 2023.09.16