Given the head
of a linked list and two integers m
and n
. Traverse the linked list and remove some nodes in the following way:
- Start with the head as the current node.
- Keep the first
m
nodes starting with the current node. - Remove the next
n
nodes - Keep repeating steps 2 and 3 until you reach the end of the list.
Return the head of the modified list after removing the mentioned nodes.
Follow up question: How can you solve this problem by modifying the list in-place?
Example 1:
Input: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3 Output: [1,2,6,7,11,12] Explanation: Keep the first (m = 2) nodes starting from the head of the linked List (1 ->2) show in black nodes. Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes. Continue with the same procedure until reaching the tail of the Linked List. Head of linked list after removing nodes is returned.
Example 2:
Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3 Output: [1,5,9] Explanation: Head of linked list after removing nodes is returned.
Example 3:
Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 3, n = 1 Output: [1,2,3,5,6,7,9,10,11]
Example 4:
Input: head = [9,3,7,7,9,10,8,2], m = 1, n = 2 Output: [9,7,8]
Constraints:
- The given linked list will contain between
1
and10^4
nodes. - The value of each node in the linked list will be in the range
[1, 10^6]
. 1 <= m,n <= 1000
删除链表 M 个节点之后的 N 个节点。
给定链表 head 和两个整数 m 和 n. 遍历该链表并按照如下方式删除节点:
开始时以头节点作为当前节点.
保留以当前节点开始的前 m 个节点.
删除接下来的 n 个节点.
重复步骤 2 和 3, 直到到达链表结尾.
在删除了指定结点之后, 返回修改过后的链表的头节点.进阶问题: 你能通过就地修改链表的方式解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道链表题。链表题如果在面试中出现,属于送分题,一定要会。
题意不难懂,对于给定的 input 链表,我们先保留 m 个节点,再跳过 n 个节点,以此交替,直到遍历完链表。那么做法也是很直接,我们给两个变量 i 和 j 分别去追踪到底数了几个节点了。这里我们还需要一个 pre 节点,记录需要跳过的 n 个节点之前的一个节点,这样在跳过 n 个节点之后,我们可以把跳过部分之前的和之后的节点连在一起。代码应该很好理解。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public ListNode deleteNodes(ListNode head, int m, int n) { 3 ListNode cur = head; 4 ListNode pre = null; 5 while (cur != null) { 6 int i = m; 7 int j = n; 8 while (cur != null && i > 0) { 9 pre = cur; 10 cur = cur.next; 11 i--; 12 } 13 while (cur != null && j > 0) { 14 cur = cur.next; 15 j--; 16 } 17 pre.next = cur; 18 } 19 return head; 20 } 21 }