1. 程式人生 > >劍指Offer-52 兩個連結串列的第一個公共結點

劍指Offer-52 兩個連結串列的第一個公共結點

題目:

輸入兩個連結串列,找出它們的第一個公共結點。

解答:

第一種,蠻力法,時間複雜度為O(mn),不需要輔助空間

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

class Solution(object):
    def findFirstCommonNode(self, headA, headB):
        """
        :type headA, headB: ListNode
        :rtype: ListNode
        """
common = None a = headA while(a): b = headB while(b): if b == a: return a b = b.next a = a.next return common

第二種,使用棧,時間和空間複雜度為O(m+n)

# Definition for singly-linked list.
# class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def findFirstCommonNode(self, headA, headB): """ :type headA, headB: ListNode :rtype: ListNode """ stackA, stackB = [], [] a,
b = headA, headB while(a): stackA.append(a) a = a.next while(b): stackB.append(b) b = b.next last = None while(stackA and stackB): ag, bg = stackA.pop(), stackB.pop() if ag == bg: last = ag return last

第三種,時間複雜度為O(m + n),不需要輔助空間

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def findFirstCommonNode(self, headA, headB):
        """
        :type headA, headB: ListNode
        :rtype: ListNode
        """
        if not headA or not headB:
            return None
        a, b = headA, headB
        lenA, lenB = 0, 0
        while(a):
            lenA += 1
            a = a.next
        while(b):
            lenB += 1
            b = b.next
        last = None
        cha = lenA - lenB
        a, b = headA, headB
        if(cha > 0):
            while(cha > 0):
                a = a.next
                cha -= 1
        if(cha < 0):
            cha = -cha
            while(cha > 0):
                b = b.next
                cha -= 1
            
        while(a and b):
            if a == b:
                return a
            else:
                a, b = a.next, b.next