劍指offer 兩個鍊錶的第乙個公共結點

2021-10-06 16:38:35 字數 2046 閱讀 8484

輸入兩個鍊錶,找出它們的第乙個公共結點。(注意因為傳入資料是鍊錶,所以錯誤測試資料的提示是用其他方式顯示的,保證傳入資料是正確的)

思路一:

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def findfirstcommonnode

(self, phead1, phead2)

:# write code here

if phead1 == none or phead2 == none:

return none

nodelist1 =

nodelist2 =

nodepointer1 = phead1

nodepointer2 = phead2

while nodepointer1:

nodelist1.

(nodepointer1)

nodepointer1 = nodepointer1.next

while nodepointer2:

nodelist2.

(nodepointer2)

nodepointer2 = nodepointer2.next

for i in nodelist1:

if i in nodelist2:

return nodelist2[nodelist2.

index

(i)]

思路二:

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def findfirstcommonnode

(self, phead1, phead2)

:# write code here

ptmp1 = phead1

ptmp2 = phead2

while ptmp1 and ptmp2:

#當兩個鍊錶一樣長時直接返回頭結點

if ptmp1 == ptmp2:

return ptmp1

ptmp1 = ptmp1.next

ptmp2 = ptmp2.next

if ptmp1: #如果ptmp1是長的鍊錶 k為差值即兩個鍊錶相差多少

k =0

#尋找出長度鍊錶之間的差值

while ptmp1:

ptmp1 = ptmp1.next

k +=1

ptmp1 = phead1

ptmp2 = phead2

#先讓長的那個走k步

for i in range

(k):

ptmp1 = ptmp1.next

while ptmp1 != ptmp2:

ptmp1 = ptmp1.next

ptmp2 = ptmp2.next

return ptmp1

if ptmp2: #如果ptmp1是長的鍊錶 k為差值即兩個鍊錶相差多少

k =0

#尋找出長度鍊錶之間的差值

while ptmp2:

ptmp2 = ptmp2.next

k +=1

ptmp1 = phead1

ptmp2 = phead2

#先讓長的那個走k步

for i in range

(k):

ptmp2 = ptmp2.next

while ptmp1 != ptmp2:

ptmp1 = ptmp1.next

ptmp2 = ptmp2.next

return ptmp2

劍指offer 兩個鍊錶第乙個公共結點

題目描述 輸入兩個鍊錶,找出它們的第乙個公共結點。解題思路 用兩重迴圈,對第乙個鍊錶的每乙個結點都進行第二個鍊錶所有結點的遍歷,若發現結點相等,則將結點返回 public listnode findfirstcommonnode listnode phead1,listnode phead2 phe...

劍指offer 兩個鍊錶的第乙個公共結點(鍊錶)

輸入兩個鍊錶,找出它們的第乙個公共結點。公共節點指的是節點的指標相同 節點本身相同 而不是節點的內容相同。如果考慮暴力的方法,對於鍊錶1的每個元素,去遍歷鍊錶2,找出第乙個公共節點,這樣時間複雜度為o mn 計算開銷大 m,n分別為兩個鍊錶的長度 考慮具有公共節點的鍊錶的特徵 如果兩個鍊錶有公共節點...

劍指offer 兩個鍊錶的第乙個公共節點

題目延伸 程式設計之美中的求兩個節點是否相交 將兩個節點串在一起,若有節點,串在一起的節點就會出現環,利用一二不長不等,兩個節點在環中必然相遇。本題描述 輸入兩個鍊錶,找出它們的第乙個公共結點。分析 乙個簡單的方法是 首先遍歷兩個鍊錶得到它們的長度,就能知道哪個鍊錶比較長,以及長的鍊錶比短的鍊錶多幾...