
我的解法还是思路太局限了,哭泣
/**
* 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 temp1=headA,temp2=headB;
Set<ListNode> set = new HashSet<>();
while(temp1!=null||temp2!=null){
if(temp1!=null){
if(set.add(temp1)){
temp1 = temp1.next;
}else{
return temp1;
}
}
if(temp2!=null){
if(set.add(temp2)){
temp2 = temp2.next;
}else{
return temp2;
}
}
}
return null;
}
}
看了大佬的相遇解法惊呆了,这是什么神仙解法,挺好理解的,也蛮简单的,可当时的我就是想不到。
两个链表长度分别为L1+C、L2+C, C为公共部分的长度,按照楼主的做法: 第一个人走了L1+C步后,回到第二个人起点走L2步;第2个人走了L2+C步后,回到第一个人起点走L1步。 当两个人走的步数都为L1+L2+C时就两个家伙就相爱了
然后我根据动态图提示写了如下代码:
/**
* 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 temp1=headA,temp2=headB;
int tag=-2;
while (temp1 != temp2 && tag<1) {
if(temp1==null){
tag++;
temp1=headB;
}else{
temp1=temp1.next;
}
if(temp2==null){
tag++;
temp2=headA;
}else{
temp2=temp2.next;
}
}
if(tag>0){
return null;
}else{
return temp1;
}
}
}
看了大佬的代码后,发现它的比我写的这个更简单:
两条链表最后都指向了同一个 null (None)节点,代替了不相交的特殊情况。 非常的巧妙
震惊我了,力扣的大佬真牛皮
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode node1=headA,node2=headB;
while (node1 != node2) {
node1 = node1 != null ? node1.next : headB;
node2 = node2 != null ? node2.next : headA;
}
return node1;
}
}
216

被折叠的 条评论
为什么被折叠?



