代码随想录算法训练营第四天 | 24. 两两交换链表中的节点、19. 删除链表的倒数第 N 个结点、面试题 02.07. 链表相交、142. 环形链表 II

24. 两两交换链表中的节点

24. 两两交换链表中的节点icon-default.png?t=N7T8https://leetcode.cn/problems/swap-nodes-in-pairs/

应用虚拟节点,virtualHead,

cur、one (1)、two (2)、temp(cur.next.next.next)节点,分别进行节点的两两交换

整体思路是这样的

依次遍历

19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点icon-default.png?t=N7T8https://leetcode.cn/problems/remove-nth-node-from-end-of-list/

思路:

虚拟头节点,快慢指针,慢指针指向倒数第n+1个节点,

删除的时候,需要删除的节点 的前序节点指向 后置节点

public ListNode removeNthFromEnd(ListNode head, int n) {
       if(head==null){
           return head;
       }
       ListNode virtualHead=new ListNode(-1,head);
        ListNode fast=virtualHead;
        ListNode slow=virtualHead;
        for(int i=0;i<=n;i++){
            fast=fast.next;
        }

        while(fast!=null){
            fast=fast.next;
            slow=slow.next;
        }

        slow.next=slow.next.next;

        return virtualHead.next;
    }

面试题 02.07. 链表相交

面试题 02.07. 链表相交icon-default.png?t=N7T8https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/

思路是快慢指针,先分别计算长度,按差值进行快慢指针遍历,循环中如果有相等的,直接退出,否则无相交节点

for(int i=0;i<lA-lB;i++){
            curA=curA.next;
        }

        while(curA!=null){
            if(curA==curB){
                return curA;
            }
            
            curA=curA.next;
            curB=curB.next;
        }

142. 环形链表 II

142. 环形链表 IIicon-default.png?t=N7T8https://leetcode.cn/problems/linked-list-cycle-ii/

快慢指针,依次遍历,

先死循环,fast一次2步,slow一次1步,得出第一次相遇的节点,如果无环,fast和fast.next可能为空, 

相遇之后,fast返回头节点,重新追赶,再次相遇的地点一定是环的入口,因为都是一次1步走的,必定在环入口处相遇

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow=head,fast=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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值