【leetcode】Intersection of Two Linked Lists

題目簡述:

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:code

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.get

Notes:it

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.io

解題思路:

首先這道題目有他的特殊性,這個特殊性就在這裏的兩個鏈表若是有交集的話,那麼他們在最後面的必定都是相同的。
因此這裏催生了兩種想法:function

  1. 從後往前比較,找到最後形同的那個
  2. 從前日後比較,可是這裏要用到一個技巧。咱們首先要去獲取到這兩個鏈表的長度,而後讓長度長的那個先多走長度差的距離,最後再開始比較,第一個相同的便是。
    這裏使用了第二種思路:class

    Definition for singly-linked list.
    class ListNode:
    def init(self, x):
    self.val = x
    self.next = NoneList

    class Solution:
    @param two ListNodes
    @return the intersected ListNode
    def getIntersectionNode(self, headA, headB):
    ta = ListNode(0)
    tb = ListNode(0)
    ta = headA
    tb = headB
    la = 0
    lb = 0
    while ta != None:
    la += 1
    ta = ta.next
    while tb != None:
    lb += 1
    tb = tb.next
    if la > lb :
    ta = headA
    tb = headB
    tt = la - lb
    while tt > 0:
    ta = ta.next
    tt -= 1
    while ta != None and tb != None:
    if ta == tb:
    return ta
    ta = ta.next
    tb = tb.next
    return None技巧

    else:
             ta = headA
             tb = headB
             tt = lb -la
             while tt > 0:
                 tb = tb.next
                 tt -= 1
             while ta != None and tb != None:
                 if ta.val == tb.val:
                     return ta
                 ta = ta.next
                 tb = tb.next
             return None
相關文章
相關標籤/搜索