您的位置:首页 > 其它

LeetCode——Intersection of Two Linked Lists

2015-06-19 23:11 387 查看
Description:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

begin to intersect at node c1.

求两个链表的相交的部分

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