[编程题]两个链表的第一个公共结点
时间限制:1秒 空间限制:32768K
输入两个链表,找出它们的第一个公共结点。
给两个指针,”分别”从头到尾遍历”两个链表“,只要没遇到公共结点就继续遍历,最终两个指针到达 null 或者到达公共结点,返回之.
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==NULL ? pHead2 : p1->next);
p2 = (p2==NULL ? pHead1 : p2->next);
}
return p1;
}
};
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, Head1, Head2):
# write code here
if Head1 is None or Head2 is None:
return
p1 = Head1
p2 = Head2
while p1 != p2:
p1 = Head2 if p1 is None else p1.next
p2 = Head1 if p2 is None else p2.next
return p1
上面的if语句写法可读性差了一点,我觉得还是写标准好
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, Head1, Head2):
# write code here
if Head1 is None or Head2 is None:
return
p1 = Head1
p2 = Head2
while p1 != p2:
if p1 is None:
p1 = Head2
else:
p1=p1.next
if p2 is None:
p2 = Head1
else:
p2=p2.next
return p1