diff --git a/README.md b/README.md index 0d7df89..c49e0cb 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ - [q25_k个一组翻转链表](/src/链表操作/q25_k个一组翻转链表) - [q61_旋转链表](/src/链表操作/q61_旋转链表) - [q138_复制带随机指针的链表](/src/链表操作/q138_复制带随机指针的链表) +- [q160_相交链表](/src/链表操作/q160_相交链表) - [q206_反转链表](/src/链表操作/q206_反转链表) ### 双指针遍历/滑动窗口 diff --git a/README_EN.md b/README_EN.md index 48df09d..4946777 100644 --- a/README_EN.md +++ b/README_EN.md @@ -16,6 +16,7 @@ - [Question 25 : Reverse Nodes in k-Group](/src/链表操作/q25_k个一组翻转链表) - [Question 61 : Rotate List](/src/链表操作/q61_旋转链表) - [Question 138 : Copy List with Random Pointer](/src/链表操作/q138_复制带随机指针的链表) +- [Question 160 : Intersection of Two Linked Lists](/src/链表操作/q160_相交链表) - [Question 206 : Reverse Linked List](/src/链表操作/q206_反转链表) ### Two Pointers Traversal / Sliding Window diff --git a/src/链表操作/q160_相交链表/ListNode.java b/src/链表操作/q160_相交链表/ListNode.java new file mode 100644 index 0000000..f3da319 --- /dev/null +++ b/src/链表操作/q160_相交链表/ListNode.java @@ -0,0 +1,11 @@ +package 链表操作.q160_相交链表; + +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} diff --git a/src/链表操作/q160_相交链表/Solution.java b/src/链表操作/q160_相交链表/Solution.java new file mode 100644 index 0000000..8009847 --- /dev/null +++ b/src/链表操作/q160_相交链表/Solution.java @@ -0,0 +1,28 @@ +package 链表操作.q160_相交链表; + +import java.util.HashSet; +import java.util.Set; + +/** + * 哈希存储 + * + * 方法二:两个链表相连,快慢指针判断是否有环(省略) + */ +public class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + Set visited = new HashSet<>(); + ListNode temp = headA; + while (temp != null) { + visited.add(temp); + temp = temp.next; + } + temp = headB; + while (temp != null) { + if (visited.contains(temp)) { + return temp; + } + temp = temp.next; + } + return null; + } +}