算法-相交链表
编写一个程序,找到两个单链表相交的起始节点。
题目过长,点击链接进入:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists
来源:力扣(LeetCode)
/**
* 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) {
if(headA == null){return null;}
if(headB == null){return null;}
HashSet<ListNode> hash = new HashSet<ListNode>();
while(headA != null){
hash.add(headA);
headA = headA.next;
}
while(headB != null){
if(hash.contains(headB)){
return headB;
}
else{
headB = headB.next;
}
}
return null;
}
}
笔记:
此题的重点不是找节点的值相同,是找节点地址相同。此题应该用HashSet来求解。
新建一个HashSet对象:
HashSet<Object> hashSet = new HashSet<Object>();
使用HashSet添加一个对象:
hashset.add(Object);
//如果Object是String对象
hashSet.add(new Student("Luna", 21));
HashSet还有.contains()
方法,returns true if this set contains the specified element.