''' 題目描述 輸入兩個鏈表,找出它們的第一個公共結點。 思路一: 先求出每個鏈表的長度,分別爲a+n和b+n n表示兩個鏈表公共部分的長度,從第一個公共節點向後的每個節點都是兩個鏈表的公共節點 也就是說從第一個相同的公共節點往後的所有節點都相同 用指針1和指針2分別記錄兩個列表中當前感興趣的位置索引值 則如果a>b,相當於讓指針1比指針2多走a-b步,則找到第一個兩個指針所指向的內容相同的地方就是兩個鏈表的第一個公共節點 思路二: 對於鏈表1和鏈表2,將鏈表的每個節點分別存儲到兩個棧stack1和stack2中 然後從最後一個節點(即棧頂元素)開始從後向前遍歷原始鏈表中的元素 相當於從原始的兩個鏈表中最後一個節點開始遍歷,則最後一個元素必然是兩個鏈表最後一個公共節點 向前遍歷得到的最後一個相同的節點就是(從前向後遍歷兩個鏈表的)第一個公共節點 ''' # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindFirstCommonNode(self, pHead1, pHead2): # write code here len_1=0 len_2=0 pHead1_copy=pHead1 pHead2_copy=pHead2 while pHead1_copy: len_1+=1 pHead1_copy=pHead1_copy.next while pHead2_copy: len_2+=1 pHead2_copy=pHead2_copy.next if len_1>len_2: start1=len_1-len_2 # start2=0 for i in range(start1): pHead1=pHead1.next while(pHead1!=pHead2): pHead1=pHead1.next pHead2=pHead2.next return pHead1 elif len_2>len_1: start2=len_2-len_1 # start1=0 for i in range(start2): pHead2=pHead2.next while(pHead1!=pHead2): pHead1=pHead1.next pHead2=pHead2.next return pHead1 else: while (pHead1!= pHead2): pHead1 = pHead1.next pHead2 = pHead2.next return pHead1 # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindFirstCommonNode(self, pHead1, pHead2): # write code here stack1=[] stack2=[] p1,p2=pHead1,pHead2 while p1: stack1.append(p1) p1=p1.next while p2: stack2.append(p2) p2=p2.next while(stack1 and stack2 and stack1[-1]==stack2[-1]): stack1.pop(-1) stack2.pop(-1) if not stack1: return pHead1 if not stack2: return pHead2 return stack1[-1].next
python 兩個鏈表的第一個公共結點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.