지식/알고리즘

6일 (21. Merge Two Sorted Lists)

매우 강한사람 2023. 9. 26. 06:43
/**
 * 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 prehead = new ListNode(-1);
            ListNode cur = prehead;

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

            cur.next = list1 == null ? list2 : list1;
            return prehead.next;
        }
    }

알고리즘 풀이가 아닌 코드리뷰이다..

- ListNode 클래스에 따라, 2개의 연결리스트를 하나의 연결리스트로 만들고 오름차순 정렬을 해야한다.

 

1. while문 하나에 list1이나 list2 둘 중 하나의 리스트의 다음 노드가 존재하지 않는다면 반복문은 동작하지 않는다.

2. list1의 현재노드와 list2의 현재노드가 서로 크기를 비교하며 번갈아가면서 pre-head의 next노드가 될 것이다.

3. 언젠가는 list1이나 list2 둘 중 하나의 next노드는 null이 될 것이다. 결국 하나의 list의 노드들만 남을 것이다.

4. list1의 노드들은 pre-head에 모두 포함되어있지만 list2의 노드들이 1개 ~ 수백, 수천개가 남았다고 하더라도

cur.next = l1 == null ? l2 : l1; 가 나머지 list2의 노드들을 논리적으로 pre-head.next에 이어줄 것이다.

 

4-2 : 연결리스트는 현재노드가 다음 노드의 정보를 알고있기 때문에 논리적으로 연결되어있을뿐이다.

 

 

 

 

 

 

 

 

 

 

https://leetcode.com/problems/merge-two-sorted-lists

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com