LeetCode#1474

本文介绍了一种在单链表中每隔m个节点删除n个节点的算法实现。通过遍历链表,维护两个指针分别指向当前节点及前一个节点,调整指针完成删除操作。适用于数据结构与算法初学者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Approach 1: Traverse Linked List and Delete In Place

Intuition

The singly linked list can be traversed linearly starting from the head node. As we must delete nn nodes after every mm nodes, we must traverse the first mm nodes, store the m^{th}m
th
node and then delete the next nn nodes. To delete the nn nodes, we must make the m^{th}m
th
node point to the node next to the n^{th}n
th
node.

Algorithm

Initialize the currentNode to the head of the linked list. currentNode is the pointer that will be used to traverse each node of the linked list linearly.

Iteratively delete nn nodes after mm node and continue until we reach the end of list.

Start by iterating mm nodes. As currentNode iterates over each node, we maintain a pointer lastMNode that points to the predecessor of currentNode. After mm iterations, the lastMNode points to the m^{th}m
th
node.
Now, continue iterating over nn nodes. After nn iterations, we must delete nodes between lastMNode and currentNode
To delete nn nodes, we could simply modify the next pointer of lastMNode to point to the currentNode.
The algorithm can be illustrated with the following example

在这里插入图片描述

class Solution {
    public ListNode deleteNodes(ListNode head, int m, int n) {
        ListNode currentNode = head;
        ListNode lastMNode = head;
        while (currentNode != null) {
            // initialize mCount to m and nCount to n
            int mCount = m, nCount = n;
            // traverse m nodes
            while (currentNode != null && mCount != 0) {
                lastMNode = currentNode;
                currentNode = currentNode.next;
                mCount--;
            }
            // traverse n nodes
            while (currentNode != null && nCount != 0) {
                currentNode = currentNode.next;
                nCount--;
            }
            // delete n nodes
            lastMNode.next = currentNode;
        }
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值