辣条走起,每个月的刷题99元奖励靠大家了
今天的题目 每天的题目见github(看最新的日期): https://github.com/gzc426 具体的题目可以去牛客网对应专题去找。
每天一道剑指offer-两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
输入两个链表,找出它们的第一个公共结点。
/*
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 length1 = 0;
int length2 = 0;
ListNode p1 = pHead1,p2 = pHead2;
while(p1 != null)
{
length1++;
p1 = p1.next;
}
while(p2 != null)
{
length2++;
p2 = p2.next;
}//分别求两个链表长度
int cha = 0;
if(length1 > length2)
{//求长度差,长的先走长度差个单位
cha = length1 - length2;
p1 = pHead1;
p2 = pHead2;
for(int i=0;i<cha;i++)
p1 = p1.next;
}else{
cha = length2 - length1;
p2 = pHead2;
p1 = pHead1;
for(int i=0;i<cha;i++)
p2 = p2.next;
}
while(p1 != p2)
{//找第一个相同的节点
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}