Advertisement
olegstankoptev

Untitled

Feb 21st, 2023
1,111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.33 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     public var val: Int
  5.  *     public var next: ListNode?
  6.  *     public init() { self.val = 0; self.next = nil; }
  7.  *     public init(_ val: Int) { self.val = val; self.next = nil; }
  8.  *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
  9.  * }
  10.  */
  11. class Solution {
  12.     func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
  13.         var list1 = list1
  14.         var list2 = list2
  15.         if list1 == nil { return list2 }
  16.         if list2 == nil { return list1 }
  17.         var head = ListNode()
  18.         var curr = head
  19.         while (list1 != nil || list2 != nil) {
  20.             if (list1 != nil && list2 != nil) {
  21.                 if (list1!.val < list2!.val) {
  22.                     curr.next = ListNode(list1!.val)
  23.                     list1 = list1!.next
  24.                 } else {
  25.                     curr.next = ListNode(list2!.val)
  26.                     list2 = list2!.next
  27.                 }
  28.             } else if (list1 != nil) {
  29.                 curr.next = ListNode(list1!.val)
  30.                 list1 = list1!.next
  31.             } else {
  32.                 curr.next = ListNode(list2!.val)
  33.                 list2 = list2!.next
  34.             }
  35.             curr = curr.next ?? curr;
  36.         }
  37.         return head.next
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement