当前位置: 首页 > 后端技术 > Java

LeetCode-160-IntersectingLinkedList

时间:2023-04-01 14:06:39 Java

IntersectingLinkedList题目描述:给定两个单向链表的头节点headA和headB,请找出并返回两个单向链表相交的起始节点。如果两个链表不相交,则返回null。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode网络所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:HashSet使用java的HashSet去重,遍历headA和headB两个链表,将每个节点放入HashSet中的notRepeatNodes中。如果能放进去,说明不相交,继续遍历下一个结点;如果不能放入,因为headA和headB之间没有环,说明这个结点是相交结点,返回当前结点。最后,如果遍历后没有找到相交节点,则说明两个链表不相交,直接返回null。importjava.util.HashSet;importjava.util.Set;publicclassLeetCode_160{publicstaticListNodegetIntersectionNode(ListNodeheadA,ListNodeheadB){if(headA==null||headB==null){returnnull;}SetnotRepeatNodes=newHashSet<>();ListNodenextA=headA;ListNodenextB=headB;while(nextA!=null||nextB!=null){if(nextA!=null){if(!notRepeatNodes.add(nextA)){返回nextA;}else{nextA=nextA.next;}}if(nextB!=null){if(!notRepeatNodes.add(nextB)){返回nextB;}else{nextB=nextB.next;}}}返回空值;}publicstaticvoidmain(String[]args){ListNodeheadA=newListNode(1);headA.next=新列表节点(9);headA.next.next=newListNode(1);ListNodeheadB=newListNode(3);ListNodecommonNode=newListNode(2);headA.next.next.next=commonNode;=公共节点;commonNode.next=newListNode(4);ListNoderesult=getIntersectionNode(headA,headB);if(result==null){System.out.println("不相交");}else{系统输出。println(result.val);}}}[每日寄语]怀着宽容的心生活,世界再拥挤也会变得无限广阔,再平凡的生活也会变得充满阳光