輸入兩個鍊錶,找出它們的第乙個公共結點。
*
/c++解法
/*struct listnode
};*/
class
solution
else
while
(phead1 !=
null
)return
null;}
intfindlistlenth
(listnode* phead1)
return sum;
}
listnode*
walkstep
(listnode* phead1,
int step)
return phead1;}}
;*/class
solution
return p1;}}
;class
solution
p = phead2;
while
(p !=
null
) p = p-
>next;
}return
null;}
};*/
# -*
- 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
p1,p2 = phead1,phead2
while p1!=p2:
p1 = p1.next if p1 else phead2
p2 = p2.next if p2 else phead1
return p1
*/兩條相交的鍊錶呈y型。可以從兩條鍊錶尾部同時出發,最後乙個相同的結點就是鍊錶的第乙個相同的結點。
可以利用棧來實現。時間複雜度有o
(m + n)
, 空間複雜度為o
(m + n)
class
solution
: def findfirstcommonnode
(self,phead1,phead2):if
not phead1 or
not phead2:
return none
stack1 =
stack2 =
while phead1:
stack1.
(phead1)
phead1= phead1.next
while phead2:
stack2.
(phead2)
phead2 = phead2.next
first = none
while stack1 and stack2:
top1 = stack1.
pop(
) top2 = stack2.
pop(
)if top1 is top2:
first = top1
else
:break
return first
*/class
solution
: def findfirstcommonnode
(self, head1, head2):if
not head1 or
not head2:
return none
p1, p2= head1, head2
length1 = length2 =
0while p1:
length1 +=1
p1 = p1.next
while p2:
length2 +=1
p2 = p2.next
if length1 > length2:
while length1 - length2:
head1 = head1.next
length1 -=1
else
:while length2 - length1:
head2 = head2.next
length2 -=1
while head1 and head2:
if head1 is head2:
return head1
head1 = head1.next
head2 = head2.next
return none
*/class
solution
: def findfirstcommonnode
(self,phead1,phead2)
: result_set =
set(
)while phead1:
result_set.
add(phead1)
phead1 = phead1.next
while phead2:
if phead2 in result_set:
return phead2
phead2 = phead2.next
兩個鍊錶的第乙個公共結點
思路 獲取兩個鍊錶的長度,求的長度差n,讓長鍊表先遍歷n次,然後長鍊表和短鍊錶同時遍歷,當長鍊錶和短鍊錶相等時,即為第一公共結點。o m1 m2 public class findfirstcomnode int len1 getnodelength root1 int len2 getnodele...
兩個鍊錶的第乙個公共結點
題目 輸入兩個鍊錶,找出他們的第乙個公共結點。方法1 分別把兩個鍊錶的節點放入兩個棧裡,這樣兩個鍊錶的尾結點就位於兩個棧的棧頂,接下來比較兩個棧頂的結點是否相同。如果相同,則把棧頂彈出接著比較下乙個棧頂,直到找到最後乙個相同的結點。時間和空間複雜度都是o m n 方法2 先遍歷兩個鍊錶得到它們的長度...
兩個鍊錶的第乙個公共結點
輸入兩個鍊錶,找出它們的第乙個公共結點。分析 如果兩個單向鍊錶有公共的結點,那麼這兩個鍊錶從某乙個結點開始,他們的next結點都指向同乙個結點,但由於是單向鍊錶的結點,每個結點都只有乙個next結點,因此從第乙個公共結點開始,之後他們所有結點都是重合的,不可能出現分支。public listnode...