补Day04: 19&面试题02.07.

本文介绍了如何解决LeetCode中的三个链表问题:删除链表的倒数第N个节点,使用双指针法找出两个链表的交点,以及检测环形链表。通过实例展示了链表操作技巧和算法应用。
摘要由CSDN通过智能技术生成

19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre=new ListNode(0);
        pre.next=head;
        ListNode start =pre;
        ListNode end=pre;
        while(n!=0){
            start=start.next;
            n--;
        }
        while(start.next!=null){
            start=start.next;
            end=end.next;
        }
        end.next=end.next.next;
        return pre.next;

    }
}

回到家了,开始疯狂补欠下的。

删除链表里的结点是学校里老师讲的重点了。 

面试题 02.07. 链表相交 - 力扣(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) {
        ListNode A=headA;
        ListNode B=headB;
        while(A!=B){
            A=A!=null?A.next:headB;
            B=B!=null?B.next:headA;
        }
        return A;
        
    }
}

这个题之前在洛谷里做过类似的,用双指针方法好理解一些。

142. 环形链表 II - 力扣(LeetCode) 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast=head;
        ListNode slow=head;
        while(true){
            if(fast==null||fast.next==null)
            return null;
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow)
            break;
        }
        fast=head;
        while(slow!=fast){
            slow=slow.next;
            fast=fast.next;
        }
        return fast;
        
    }
}

这题用快慢指针,关键在于推出fast=slow+nb(环的结点数)。 

 

 

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值