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 }