当前位置:网站首页>12--合并两个有序链表

12--合并两个有序链表

2022-06-24 06:56:00 JH_Cao

合并两个有序链表

Github链接

  • 思路很简单,对链表写起来不熟悉
  • 递归思路
    在这里插入图片描述
class xiapi_12 {
    
    func mergeTwoLists(_ list1: ListNode12?, _ list2: ListNode12?) -> ListNode12? {
    
        if list2 == nil {
    
            return list1
        }
        if list1 == nil {
    
            return list2
        }
        
        if list1?.val ?? 0 < list2?.val ?? 0 {
    
            list1?.next = mergeTwoLists(list1?.next, list2)
            return list1
        } else {
    
            list2?.next = mergeTwoLists(list2?.next, list1)
            return list2
        }
    }
}

public class ListNode12 {
    
    public var val: Int
    public var next: ListNode12?
    public init() {
     self.val = 0; self.next = nil; }
    public init(_ val: Int) {
     self.val = val; self.next = nil; }
    public init(_ val: Int, _ next: ListNode12?) {
     self.val = val; self.next = next; }
}
原网站

版权声明
本文为[JH_Cao]所创,转载请带上原文链接,感谢
https://blog.csdn.net/JH_Cao/article/details/125436926