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 |