您的位置:首页 > 其它

160. Intersection of Two Linked Lists

2016-06-10 21:29 246 查看
题目:https://leetcode.com/problems/intersection-of-two-linked-lists/

代码:

/**
* 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 headA, ListNode headB) {
if(headA==null||headB==null)
return null;
if(headA==headB)
return headA;
ListNode ta,tb;
ta = headA;
int lengtha=1,lengthb=1;
while(ta.next!=null)
{
lengtha++;
ta = ta.next;
}
tb = headB;
while(tb.next!=null)
{
lengthb++;
tb = tb.next;
}
if(ta!=tb)
return null;
ta = headA;
tb = headB;
while(lengtha>lengthb)
{
ta = ta.next;
lengtha--;
}
while(lengtha<lengthb)
{
tb = tb.next;
lengthb--;
}
while(ta!=null)
{
if(ta==tb)
return ta;
ta = ta.next;
tb = tb.next;
}
return null;
}
}
2ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: