思路
较长的链表先进行遍历至两个链表的长度一致,注意考虑链表为空的时候。
从链表的定义可知,若两个单向链表有公共结点,那从某一结点开始,两个链表的next均指向同一个值。
公共结点:第一个值相同且next指向相同的结点。
/*
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) //有链表为空时返回null
return null;
int l1= Nlength(pHead1);
int l2= Nlength(pHead2);
ListNode p1= pHead1;
ListNode p2= pHead2;
int dis= l1-l2;
if (l1< l2){
p1= pHead2;
p2= pHead1;
dis= l2-l1;
}
for(int i=0;i< dis; i++){
p1=p1.next;
}
while ((p1 != null)&&(p2!= null)&&(p1!= p2))
{
p1= p1.next;
p2= p2.next;
}
ListNode pp = p1;
return pp;
}
//}
private int Nlength(ListNode head){
int length = 0;
ListNode l= head;
while(l.next != null){
length ++;
l= l.next;
}
return length;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2){
int l1= Nlength(pHead1);
int l2= Nlength(pHead2);
ListNode p1= pHead1;
ListNode p2= pHead2;
int dis= l1-l2;
if (l1< l2){
p1= pHead2;
p2= pHead1;
dis= l2-l1;
}
for(int i=0;i< dis; i++){
p1=p1.next;
}
while ((p1.next != null)&&(p2.next != null)&&(p1.next != p2.next))
{
p1= p1.next;
p2= p2.next;
}
ListNode pp = p1;
return pp;
}
//}
private int Nlength(ListNode head){
int length = 0;
ListNode l= head;
while(l.next != null){
length ++;
l= l.next;
}
return length;
}
}
本文介绍了如何使用Python解决链表问题,通过比较两个链表的长度并同步遍历,找到它们的第一个公共节点。特别关注了链表为空的情况。核心代码展示了遍历和同步操作的过程。
332

被折叠的 条评论
为什么被折叠?



