-
[LeetCode] 21. Merge Two Sorted Lists / Swift프로그래밍/코딩테스트 2021. 6. 20. 19:54
[문제 보기]
더보기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.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = [] Output: []
Example 3:
Input: l1 = [], l2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both l1 and l2 are sorted in non-decreasing order.
https://leetcode.com/problems/merge-two-sorted-lists/
간단한 연결리스트 문제였다.
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ class Solution { func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { var p1 = l1 var p2 = l2 var ans = ListNode() let first = ans while p1 != nil || p2 != nil { if let v1 = p1?.val, let v2 = p2?.val { if v1 < v2 { ans.next = ListNode(v1) ans = ans.next! p1 = p1!.next } else { ans.next = ListNode(v2) ans = ans.next! p2 = p2!.next } } else { var temp = p1 if temp == nil { temp = p2 } while temp != nil { ans.next = ListNode(temp!.val) ans = ans.next! temp = temp!.next } break } } // var temp: ListNode? = first.next // while temp != nil { // print(temp!.val) // temp = temp!.next // } return first.next } }
반응형'프로그래밍 > 코딩테스트' 카테고리의 다른 글
[Contest 246] 1903. Largest Odd Number in String / Swift (0) 2021.06.21 [LeetCode] 617. Merge Two Binary Trees / Swift (0) 2021.06.21 [1926번] 그림 / Swift (0) 2021.06.20 [2020 카카오 인턴십] 경주로 건설 / Swift (0) 2021.06.17 [프로그래머스] 가장 긴 팰린드롬 / Swift (0) 2021.06.17