您的位置:首页 > 其它

Intersection of Two Linked Lists

2016-07-03 02:12 267 查看
Write a program to find the node at which the intersection of two singly linked lists begins.

Notice

If the two linked lists have no intersection at all, return
null
.

The linked lists must retain their original structure after the function returns.

You may assume there are no cycles anywhere in the entire linked structure.

Example

The following two linked lists:

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

begin to intersect at node c1.

分析:

需要先得到两个List的长度,然后让长的List先走,等到长度一致的时候,比较两个指针是否指向同一个node,如果是,返回该node。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
* cnblogs.com/beiyeqingteng
*/
public ListNode getIntersectionNode(ListNode h1, ListNode h2) {
if (h1 == null || h2 == null) return null;

int size1 = size(h1);
int size2 = size(h2);

for (int i = 0; i < Math.abs(size1 - size2); i++) {
if (size1 > size2) {
h1 = h1.next;
} else {
h2 = h2.next;
}
}

while (h1 != h2) {
h1 = h1.next;
h2 = h2.next;
}

return h1;
}

private int size(ListNode head) {
int total = 0;
while (head != null) {
total++;
head = head.next;
}
return total;
}
}


转载请注明出处:cnblogs.com/beiyeqingteng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: