编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
思路:类似快慢指针,即双指针
—官方给的答案:
当p1到达链表尾时,让p1 = headB
当p2到达链表尾时,让p2 = headA
这样一定有 p1 == p2
如果p1、p2有交点,那p1 == p2 && p1!=null
如果没有,p1 == p2 && p1==null;
–分析原因:
我的原因不太对推荐看leetcode官方分析,但这种题,看了也不太好自我分析
-话说以前做过,但这次做第二次还是不会,分析原因真的有用吗?
—怎么判断有交点,p1 == p2时
—如果两链表长度相等,那可以出现p1 == p2
—如果两链表不相等,那一次同时遍历两个链表不可以出现p1 == p2
—我往把同时改成分别那样想了,但
—由于相交节点之前的长度不一样,我们让短的,类似于走的快的,走完后,去走长的那条路,让长的,走完后,去走短的路,,俩指针距第一交点的长度都一样了,那肯定可以相交。
流程图真好用,一次通过,还可以帮助找bug
/**
-
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) {
ListNode p1 = headA;
ListNode p2 = headB;if(p1 == null || p2 == null) return null; int count1 = 1; int count2 = 1; while( p1!=p2){ p1 = p1.next; p2 = p2.next; if(p1 == null){ if(count1 == 1){ p1 = headB; count1++; }else{ return null; } } if(p2 == null){ if(count2 == 1){ count2++; p2 = headA; }else{ return null; } } } return p1;
}
}