Advertisement
Alexxik

Untitled

Sep 18th, 2023
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.62 KB | None | 0 0
  1. // MARK: - Смержить 2 linked lists
  2.  
  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. func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
  12.     if l1 == nil || l2 == nil { return l1 == nil ? l2 : l1 }
  13.     if l1!.val <= l2!.val {
  14.         l1?.next = mergeTwoLists(l1?.next, l2)
  15.         return l1
  16.     } else {
  17.         l2?.next = mergeTwoLists(l1, l2?.next)
  18.         return l2
  19.     }
  20. }
  21.  
  22. // без рекурсии
  23. func mergeTwoList1(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
  24.     guard l1 != nil else { return l2 }
  25.     guard l2 != nil else { return l1 }
  26.  
  27.     let mockHead: ListNode? = ListNode(0, nil) //если придет нил, чтобы проект не упал
  28.     var l1 = l1
  29.     var l2 = l2
  30.     var endSortedList: ListNode? = mockHead
  31.  
  32.     while l1 != nil && l2 != nil {
  33.         if l1!.val <= l2!.val {
  34.             endSortedList?.next = l1
  35.             l1 = l1?.next
  36.         } else {
  37.             endSortedList?.next = l2
  38.             l2 = l2?.next
  39.         }
  40.         endSortedList = endSortedList?.next
  41.     }
  42.     endSortedList?.next = (l1 == nil) ? l2 : l1
  43.     return mockHead?.next
  44. }
  45.  
  46.  
  47.  
  48. let thirdNode = ListNode(4, nil)
  49. let secondNode = ListNode(3, thirdNode)
  50. let firstNode = ListNode(1, secondNode)
  51.  
  52. let node3 = ListNode(6, nil)
  53. let node2 = ListNode(5, node3)
  54. let node1 = ListNode(2, node2)
  55. let test1 = mergeTwoList1(firstNode, node1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement