1. 程式人生 > >LeetCode160:Intersection of Two Linked Lists

LeetCode160:Intersection of Two Linked Lists

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.

LeetCode:連結

劍指Offer_程式設計題36:兩個連結串列的第一個公共結點是一道題。

第一種方法:先依次遍歷兩個連結串列,記錄兩個連結串列的長度m和n,如果m>n,那麼我們就先讓長度為m的連結串列走m-n個結點,然後兩個連結串列同時遍歷,當遍歷到相同的結點的時候停止即可。對於 m < n,同理。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA:
            return None
        if not headB:
            return None
        lengthA = self.getcount(headA)
        lengthB = self.getcount(headB)
        if lengthA > lengthB:
            longlength = headA
            shortlength = headB
        else:
            longlength = headB
            shortlength = headA
        for i in range(abs(lengthA-lengthB)):
            longlength = longlength.next
        while longlength and shortlength:
            if longlength == shortlength:
                return longlength
            longlength = longlength.next
            shortlength = shortlength.next
        return None

    def getcount(self, head):
        count = 0
        while head:
            count += 1
            head = head.next
        return count

第二種方法:我們可以把兩個連結串列拼接起來,一個pHead1在前pHead2在後,一個pHead2在前pHead1在後。這樣,生成了兩個相同長度的連結串列,那麼我們只要同時遍歷這兩個表,就一定能找到公共結點。

就是都讓遍歷的時候長度統一

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return None
        pheadA = headA
        pheadB = headB
        while pheadA != pheadB:
            pheadA = pheadA.next if pheadA else headB
            pheadB = pheadB.next if pheadB else headA
        return pheadA