[Swift]LeetCode160. 相交鏈表 | Intersection of Two Linked Lists

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-hblfzbds-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Write a program to find the node at which the intersection of two singly linked lists begins.node

For example, the following two linked lists:git

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.github

Notes:微信

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

編寫一個程序,找到兩個單鏈表相交的起始節點。spa

例如,下面的兩個鏈表:code

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

在節點 c1 開始相交。htm

注意:blog

  • 若是兩個鏈表沒有交點,返回 nil.
  • 在返回結果後,兩個鏈表仍須保持原有的結構。
  • 可假定整個鏈表結構中沒有循環。
  • 程序儘可能知足 O(n) 時間複雜度,且僅用 O(1) 內存。

 1 class Solution {
 2     func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode? ) -> ListNode? {
 3         if headA == nil || headB == nil {
 4             return nil
 5         }
 6         
 7         var a = headA
 8         var b = headB
 9         while (a !== b) {
10             if a != nil {
11                 a = a?.next
12             } else {
13                 a = headB
14             }
15             
16             if b != nil {
17                 b = b?.next
18             } else {
19                 b = headA
20             }
21         }
22         return a
23     }
24     
25     public class ListNode: Equatable {
26         
27         public var val: Int
28         public var next: ListNode?
29         
30         public init(_ val: Int) {
31             self.val = val
32             self.next = nil
33         }
34         
35         public static func ==(lhs: Solution.ListNode, rhs: Solution.ListNode) -> Bool {
36             return lhs.val == rhs.val && lhs.next == rhs.next
37         }  
38     }
39 }
相關文章
相關標籤/搜索