【Leetcode】Java:链表


参考了很多大佬的题解,仅作为自己学习笔记用。


1、160. 相交链表

题意:

编写一个程序,找到两个单链表相交的起始节点。如果两个链表没有交点,返回 null;在返回结果后,两个链表仍须保持原有的结构。可假定整个链表结构中没有循环。
如下面的两个链表:
在这里插入图片描述

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

在这里插入图片描述

输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。

题解1:

如果链表 A 的指针 l1 走到末尾,就从链表 B 再开始走;
如果链表 B 的指针 l2 走到末尾,就从链表 A 再开始走。
相遇的时候,两个指针走的是一样长的路程。

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
   
        ListNode l1 = headA, l2 = headB;
        while(l1 != l2){
   
            l1 = l1 == null ? headB : l1.next;
            l2 = l2 == null ? headA : l2.next;
        }
        return l1;
    }

题解2:

将其中一个链表节点放入 Set 中,再放另一个链表节点,如果 Set 已经包含了该节点,表明已经存在,返回该节点。

    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;
    }

题解3:

统计两个链表的长度,长的链表先走,然后再长的和短的一起走,会相遇。

2、206. 反转链表

题意:

反转一个单链表。

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

题解1:

双指针。

    public ListNode reverseList(ListNode head) {
   
        ListNode pre = null, cur = head;
        while(cur != null){
   
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

题解2:

递归。

    public ListNode reverseList(ListNode head) {
   
        return recur(head, null);
    }

    public ListNode recur(ListNode cur, ListNode pre) {
   
        if(cur == null) return pre;

        ListNode res = recur(cur.next, cur);
        cur.next = pre;
        return res;
    }

题解3:

头插法。

    public ListNode reverseList(ListNode head) {
   
        ListNode newHead = new ListNode(-1);
        while(head != null){
   
            ListNode next = head.next;
            head.next = newHead.next;
            newHead.next = head
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值