为有牺牲多壮志,敢教日月换新天。

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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10109542.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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

For example, the following two linked lists:

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

begin to intersect at node c1.

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.

编写一个程序,找到两个单链表相交的起始节点。

例如,下面的两个链表:

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

在节点 c1 开始相交。

注意:

  • 如果两个链表没有交点,返回 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 }

 

posted @ 2018-12-12 17:22  为敢技术  阅读(403)  评论(0编辑  收藏  举报