/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode pHead1, ListNode pHead2) {
int len1=1, len2=1;
ListNode t1=pHead1, t2=pHead2;
if(t1==null||t2==null) return null;
while(t1.next!=null)
{
len1++;
t1=t1.next;
}
while(t2.next!=null)
{
len2++;
t2=t2.next;
}
if(t1!=t2) return null;
if(len1>len2)
{
ListNode tmp=pHead1;
pHead1=pHead2;
pHead2=tmp;
//len1^=len2^=len1^=len2;
int t=len2;
len2=len1;
len1=t;
}
for(int i=1; i<=len2-len1; i++)
{
pHead2=pHead2.next;
}
while(pHead1!=pHead2)
{
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return pHead1;
}
}
LeetCode 160. Intersection of Two Linked Lists(两个链表的第一个公共结点)
最新推荐文章于 2023-07-27 20:37:08 发布