Problem solving/Algorithms

[LeetCode] 21. Merge Two Sorted Lists (C#)

Young_A 2021. 1. 29. 14:14

LeetCode - Problems - Algorithms - 21. Merge Two Sorted Lists

Problem Description

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

 

My Solution (C#)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;

        ListNode head = new ListNode();
        ListNode walk = head;
        while (true)
        {
            if (l1.val < l2.val)
            {
                walk.next = l1;
                l1 = l1.next;
            }
            else
            {
                walk.next = l2;
                l2 = l2.next;
            }
            walk = walk.next;

            if (l1 == null)
            {
                walk.next = l2;
                return head.next;
            }
            if (l2 == null)
            {
                walk.next = l1;
                return head.next;
            }
        }
    }
}

์–ผ๋งˆ์ „์— python์œผ๋กœ๋„ ํ’€์—ˆ๋˜ ๋ฌธ์ œ๋ผ์„œ ํ’€์ด๋Š” ์ƒ๋žตํ•œ๋‹ค...!

๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ์•ˆ ์˜ฌ๋ ธ์—ˆ๋‚˜๋ณด๋‹ค~

ํ’€์ด๋Š” ๊ฐ„๋‹จํ•˜๋‹ค.

์ผ๋‹จ l1์ด ๋น„์–ด์žˆ์œผ๋ฉด l2๋ฅผ, l2๊ฐ€ ๋น„์–ด์žˆ์œผ๋ฉด l1์„ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•œ๋‹ค.

 

์šฐ๋ฆฌ๊ฐ€ ์ž‘์—…ํ•˜๋Š” ListNode๋Š” next์™€ value ๊ฐ’๋งŒ ์žˆ์œผ๋ฏ€๋กœ, ์ž์ฒด์ ์œผ๋กœ head๋ฅผ ๋งŒ๋“ค์–ด์ค€๋’ค, walk ์ฆ‰, ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ๊ฐ™์ด ๋”ฐ๋ผ์„œ ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ์—ฐ๊ฒฐํ•ด์ค„ walk ๊ฐ’์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.

 

๋‚˜๋Š” ์ค‘๊ฐ„์— l1์ด๋‚˜ l2์˜ ๊ฐ’์„ ๋ชจ๋‘ ์ด์šฉํ•˜๊ฒŒ ๋˜๋ฉด return์„ ์ด์šฉํ•ด method๋ฅผ ๋๋งˆ์น  ์ƒ๊ฐ์ด๋ฏ€๋กœ true ๊ฐ’์„ ํ™•์ธํ•˜๋Š” while ๋ฐ˜๋ณต๋ฌธ์„ ์—ด์–ด์ฃผ์—ˆ๋‹ค.

 

์ด ํ›„ ํ˜„์žฌ l1๊ณผ l2์˜ ๊ฐ’์„ ๋น„๊ตํ•ด ํฐ ๊ฐ’์„ walk.next์— ์—ฐ๊ฒฐํ•ด์ฃผ๊ณ , ์—ฐ๊ฒฐ๋œ ๊ฐ’์˜ ๋‹ค์Œ ๊ฐ’์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. (e.g. l1 = l1.next;)

 

ํ˜„์žฌ walk ๊ฐ’์˜ next๊ฐ’์„ walk์— ๋‹ค์‹œ ์ €์žฅํ•œ๋‹ค.

 

๋งŒ์•ฝ l1์ด๋‚˜ l2์˜ ๊ฐ’์ด null์ผ ๊ฒฝ์šฐ ๋น„์–ด์žˆ์ง€ ์•Š์€ ๋‚˜๋จธ์ง€ node๋ฅผ walk.next์— ์—ฐ๊ฒฐํ•ด์ค€๋‹ค.

๋‚˜๋จธ์ง€ ๊ฐ’์€ ๊ธฐ์กด์— ์—ฐ๊ฒฐ๋œ node๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ›์•„์˜ค๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ”๋กœ head.next ๊ฐ’์„ ๋ฆฌํ„ดํ•ด์ฃผ๋ฉด ์˜ฌ๋ฐ”๋ฅธ node list๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋œ๋‹ค.

 

'Problem solving > Algorithms' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] 27. Remove Element (C#)  (0) 2021.01.30
[LeetCode] 26. Remove Duplicates from Sorted Array (C#)  (0) 2021.01.29
[LeetCode] 20. Valid Parentheses (C#)  (0) 2021.01.26
[LeetCode] 14. Longest Common Prefix (C#)  (0) 2021.01.25
[LeetCode] 13. Roman to Integer (C#)  (0) 2021.01.24