您的位置:首页 > 其它

Intersection of Two Linked Lists

2015-04-17 15:45 211 查看
先计算两个链表长度,再对链表进行对齐

/**
* 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(null ==headA || null == headB) return null;
int lengthA = 0, lengthB = 0;
ListNode pointerA = headA;
ListNode pointerB = headB;;
while(null != pointerA) {
lengthA++;
pointerA = pointerA.next;
}
while(null != pointerB) {
lengthB++;
pointerB = pointerB.next;
}
pointerA = iThNode((lengthA<lengthB ? 1 : lengthA - lengthB +1), headA);
pointerB = iThNode((lengthA<lengthB ? lengthB - lengthA +1 : 1), headB);
while(pointerA != pointerB){
pointerA = pointerA.next;
pointerB = pointerB.next;
}
return pointerA;
}

//fucn ithNode, return the ith node of ListNode head
public ListNode iThNode(int i, ListNode node){
if(i < 1) return null;
for(int j = 1; j < i; j++) node = node.next;
return node;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: