题目:
输入两个链表,找出它们的第一个公共结点。
解题思路:
最暴力的解法是双重遍历,假设两个链表的长度分别为m和n,那么这种解法的时间复杂度是O(mn),第二种解法是从后往前遍历这两个链表,即将两个链表先反转,从后往前遍历。可以采用辅助栈的结构。这种解法的时间复杂度为O(m+n),第三种解法是先求两个链表的长度,求出长度差,然后给两个链表分别设置两个指针,让长的链表先走差值的步数,此种解法的时间复杂度为O(m+n)。下面算法实现了第三种解法:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null){
return null;
}
int len1 = length(pHead1);
int len2 = length(pHead2);
ListNode temp1 = pHead1;
ListNode temp2 = pHead2;
if(len1==len2)
return pHead1;
if(len1>len2){
int res = len1 - len2;
for(int i=0;i<res;i++){
temp1 = temp1.next;
}
while(temp1!=temp2){
temp1 = temp1.next;
temp2 = temp2.next;
}
return temp1;
}
if(len1<len2){
int res = len2 - len1;
for(int i=0;i<res;i++){
temp2 = temp2.next;
}
while(temp1!=temp2){
temp1 = temp1.next;
temp2 = temp2.next;
}
return temp1;
}
return null;
}
public int length(ListNode head){
if(head==null)
return 0;
ListNode temp = head;
int count = 0;
while(temp.next!=null){
count++;
temp = temp.next;
}
return count;
}
}