LeetCode 160. 相交链表;LeetCode 206. 反转链表

image
思路是创建哈希先暂存第一条链表,再遍历第二个看是否相交

涉及到的HashSet(因为我不知道这方面的东西)

// 1. 创建 HashSet,存放 ListNode 节点
Set<ListNode> set = new HashSet<>();

// 2. 添加节点到集合
set.add(节点);

// 3. 检查节点是否在集合中
if (set.contains(节点)) {
    // 存在
}

实现:


public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
       Set<ListNode> set=new HashSet<>();
       while(headA!=null){
        set.add(headA);
        headA=headA.next;
       }

       while(headB!=null){
        if(set.contains(headB)){
            return headB;
        }
        headB=headB.next;
       }

       return null;
    
}
}

image
思路是设计三个指针,两个用来推进,一个用来暂存节点防止断链,核心是反转指针

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode q=null;
        ListNode p=head;
        
        while(p!=null){
            ListNode n=p.next;//暂存下一节点
            p.next=q;//翻转指针
            q=p;//后移
            p=n;//后移
        }

        return q;
    }
}
posted @ 2026-04-21 16:34  mwhB  阅读(2)  评论(0)    收藏  举报