Write a program to find the node at which the intersection of two singly linked lists begins.
https://assets.leetcode.com/uploads/2018/12/13/160_statement.png
begin to intersect at node c1.
Notice:
代码:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
int depthA = depth(headA);
int depthB = depth(headB);
ListNode pA = headA;
ListNode pB = headB;
if(depthA >= depthB){
while(depthA > depthB){
pA = pA.next;
depthA--;
}
}else{
while(depthB > depthA){
pB = pB.next;
depthB--;
}
}
while(pA != null && pB != null){
if(pA==pB) break;
pA = pA.next;
pB = pB.next;
}
return pA;
}
private int depth(ListNode head){
int dep = 0;
ListNode cur = head;
while(cur != null){
dep++;
cur = cur.next;
}
return dep;
}
}
注意:
书写代码自己要规范,不然容易自己犯一些很傻的错误
LeetCode 链表 160. Intersection of Two Linked Lists
原文:https://www.cnblogs.com/muche-moqi/p/12398496.html