原题
输入两个链表,找出它们的第一个公共结点。
Reference Answer
思路分析
将链表中节点放入list后进行操作,对这种确定公共节点,计算数目之类的问题无往不利。
# -*- 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
if not pHead1 or not pHead2:
return None
temp = []
start1 = pHead1
start2 = pHead2
while start1:
temp.append(start1)
start1 = start1.next
while start2:
if start2 in temp:
return start2
start2 = start2.next
return None
上述方式太过暴力,时空复杂度都是 O(n);
该题的空间复杂度是可以降为 O(1)的,下面是优化版。
优化版:
我们也可以先让把长的链表的头砍掉,让两个链表长度相同,这样,同时遍历也能找到公共结点。此时,时间复杂度O(m+n),空间复杂度为O(1)。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr){
return nullptr;
}
ListNode* head1 = pHead1;
ListNode* head2 = pHead2;
ListNode* temp1 = head1;
ListNode* temp2 = head2;
int length = 0;
while (head1 && head2){
head1 = head1->next;
head2 = head2->next;
length ++;
}
while(head1){
temp1 = temp1->next;
head1 = head1->next;
}
while(head2){
temp2 = temp2->next;
head2 = head2->next;
}
while (temp1 && temp2){
if (temp1 == temp2){
return temp1;
}
temp1 = temp1->next;
temp2 = temp2->next;
}
return NULL;
}
};