【算法】相交链表
一开始我是这么写了一下,但是!虽然两个链表包含相同的数值序列(1 → 8 → 4 → 5),但关键问题在于:这些是数值相同的不同节点实例,而不是同一个节点对象。
代码使用HashSet
存储的是LinkNode
对象的引用,而不是节点的值。当检查set.contains(tmpB)
时,它比较的是对象引用是否相同,而不是节点值是否相等。
所以其实如果要构造这个相交链表的话,可以如下:
private static LinkNode test2(){LinkNode node1 = new LinkNode(1);LinkNode node8 = new LinkNode(8);LinkNode node4 = new LinkNode(4);LinkNode node5 = new LinkNode(5);LinkNode A= new LinkNode(4);LinkNode B= new LinkNode(5);A.next = node1;A.next.next = node8;A.next.next.next = node4;A.next.next.next.next = node5;B.next = new LinkNode(0);B.next.next = node1;B.next.next.next = node8;B.next.next.next.next = node4;B.next.next.next.next.next = node5;Set<LinkNode> visited= new HashSet<>();LinkNode tmpA = A;while(tmpA!=null){visited.add(tmpA);tmpA = tmpA.next;}LinkNode tmpB = B;while(tmpB!=null){if(visited.contains(tmpB)){return tmpB;}tmpB = tmpB.next;}return null;}
法二双指针
ListNode tmpA = headA;ListNode tmpB = headB;while(tmpA!=tmpB){tmpA = (tmpA==null?headB:tmpA.next);tmpB = (tmpB==null?headA:tmpB.next);}
法三 长度差。但是要计算长度,然后判断长短,感觉这个太不优雅了。思路最简单这个。