All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 07, 2024
Last updated : July 01, 2024
Related Topics : Linked List
Acceptance Rate : 73.37 %
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteNodes(struct ListNode* head, int m, int n) {
struct ListNode* current = head;
for (int i = 1; i < m && current; i++) {
current = current->next;
}
while (current) {
for (int j = 0; j < n && current->next; j++) {
struct ListNode* temp = current->next;
current->next = current->next->next;
free(temp); // Freeing the values since they're now deleted
}
for (int i = 0; i < m && current; i++) {
current = current->next;
}
}
return head;
}
/**
* 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 deleteNodes(ListNode head, int m, int n) {
ListNode current = new ListNode(0);
current.next = head;
ListNode output = current;
while (current != null) {
for (int i = 0; i < m && current != null; i++) {
current = current.next;
}
if (current == null) {
break;
}
for (int j = 0; j < n && current.next != null; j++) {
current.next = current.next.next;
}
}
return output.next;
}
}