题目
描述
输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
数据范围: n≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)
思路
先各自走各自的路,走到头时再去走对方的路,那么一定会存在一个节点相同,如果没有公共节点也是可以的,都会同时走到最后。
代码
python版本:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
p1 = pHead1
p2 = pHead2
while(p1!=p2):
if p1 != None:
p1 = p1.next
else:
p1 = pHead2
if p2 != None:
p2 = p2.next
else:
p2 = pHead1
return p1
c++版本:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *p1 = pHead1;
ListNode *p2 = pHead2;
while(p1 != p2){
p1 = !p1 ? pHead2 : p1->next;
p2 = !p2 ? pHead1 : p2->next;
}
return p1;
}
};