面试题02.07:

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

方案一

  1. public class Solution {
  2. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  3. ListNode tempA = headA;
  4. ListNode tempB = headB;
  5. if (tempA == tempB){
  6. return tempA;
  7. }
  8. HashSet<ListNode> set = new HashSet<>();
  9. while (tempA != null || tempB != null) {
  10. if (tempA != null && tempB != null && tempA == tempB){
  11. return tempA;
  12. }
  13. if (tempA != null && set.contains(tempA)) {
  14. return tempA;
  15. }
  16. if (tempB != null && set.contains(tempB)) {
  17. return tempB;
  18. }
  19. set.add(tempA);
  20. set.add(tempB);
  21. if (tempA != null){
  22. tempA = tempA.next;
  23. }
  24. if (tempB != null){
  25. tempB = tempB.next;
  26. }
  27. }
  28. return null;
  29. }
  30. }

参考文献

  1. 「代码随想录」带你搞定链表!试题02.07.链表相交