标签:
问题描述
RT.
解决思路
(1) 两链表都是单向链表:判断两链表的末尾节点是否相同;
(2) 两链表中一个有环,一个没环:不可能相交;
(3) 两链表都有环:slow-fast双指针方法。
程序
public class ListIntersection {
// two single list
public boolean isIntersectionOfTwoSingleList(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return false;
}
// whether the end of two list is same
ListNode endOfList1 = getEndOfList(l1);
ListNode endOfList2 = getEndOfList(l2);
return endOfList1 == endOfList2;
}
private ListNode getEndOfList(ListNode head) {
if (head == null) {
return null;
}
ListNode node = head;
while (node.next != null) {
node = node.next;
}
return node;
}
// two list with cycle
public boolean isIntersectionOfTwoListWithCycle(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return false;
}
ListNode slow = l1, fast = l2;
while (fast.next != null || fast != null || slow != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
标签:
原文地址:http://www.cnblogs.com/harrygogo/p/4614277.html