План курса / Все задачи / Алгоритмы и структуры данных
Удаление с конца
средне
# решено
Дана голова односвязного списка head. Необходимо удалить n-й узел с конца списка и вернуть голову измененного списка.
Пример 1:
Ввод: head = [1,2,3,4], n = 2
Вывод: [1,2,4]
Пример 2:
Ввод: head = [1,2,3], n = 3
Вывод: [2,3]
Пример 3:
Ввод: head = [1], n = 1
Вывод: []
Ограничения:
1 <= n <= len(head)
Видео не скачано: Iframe provider detected. HLS/MP4 URL is required.. Оригинальная ссылка
Видео не скачано: [tcp @ 000001796fda6ac0] Failed to resolve hostname edge-ams-1.kinescopecdn.net: The name does not resolve for the supplied parameters
[in#0 @ 000001796fd91700] Error when loading first segment 'https://edge-ams-1.kinescopecdn.net/f6cd6a5f-6ee4-4c22-9d30-396f5a6f501b/videos/a1e01e4b-b577-426e-97d9-d58a7ad20175/assets/019620d7-ca16-784d-99ac-557a08f28934/audio_0.mp4'
[in#0 @ 000001796fd91040] Error opening input: I/O error
Error opening input file https://kinescope.io/2428d6c3-f345-4b55-9984-d2797693e7de/master.m3u8?expires=1778404402&sign=a310278063a2fe79.
Error opening input files: I/O error. Оригинальная ссылка
/**
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public static ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode dummyNode = new ListNode(0, head);
ListNode fast = dummyNode;
for (int i = 0; i < n + 1; i++) {
fast = fast.next;
}
ListNode slow = dummyNode;
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
// удаляем вершину
slow.next = slow.next.next;
return dummyNode.next;
}
}
#include <vector>
using namespace std;
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyNode = new ListNode(0);
dummyNode->next = head;
ListNode* fast = dummyNode;
for (int i = 0; i < n + 1; i++) {
fast = fast->next;
}
ListNode* slow = dummyNode;
while (fast != nullptr) {
slow = slow->next;
fast = fast->next;
}
// Удаляем вершину
ListNode* toDelete = slow->next;
slow->next = slow->next->next;
delete toDelete; // Освобождаем память удалённого узла
// Освобождаем dummyNode перед возвратом результата
ListNode* result = dummyNode->next;
delete dummyNode;
return result;
}
package main
/**
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
dummyNode := &ListNode{Val: 0, Next: head}
fast := dummyNode
for i := 0; i < n+1; i++ {
fast = fast.Next
}
slow := dummyNode
for fast != nil {
slow = slow.Next
fast = fast.Next
}
// удаляем вершину
slow.Next = slow.Next.Next
return dummyNode.Next
}
import java.util.*;
/**
* class ListNode {
* Integer val;
* ListNode next;
* ListNode() {}
* ListNode(Integer val) { this.val = val; }
* ListNode(Integer val, ListNode next) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyNode = new ListNode(0, head);
ListNode fast = dummyNode;
for (int i = 0; i < n + 1; i++) {
fast = fast.next;
}
ListNode slow = dummyNode;
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
// удаляем вершину
slow.next = slow.next.next;
return dummyNode.next;
}
}
from list_node import ListNode
# class ListNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
def remove_nth_from_end(head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummyNode = ListNode(val=0, next=head)
fast = dummyNode
for i in range(n + 1):
fast = fast.next
slow = dummyNode
while fast is not None:
slow = slow.next
fast = fast.next
# удаляем вершину
slow.next = slow.next.next
return dummyNode.next
import { ListNode } from './listNode.js';
/**
* class ListNode {
* constructor(val, next) {
* this.val = val;
* this.next = (next === undefined ? null : next);
* }
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @returns {ListNode}
*/
export function removeNthFromEnd(head, n) {
let dummyNode = new ListNode(0, head);
let fast = dummyNode;
for (let i = 0; i < n + 1; i++) {
fast = fast.next;
}
let slow = dummyNode;
while (fast !== null) {
slow = slow.next;
fast = fast.next;
}
// удаляем вершину
slow.next = slow.next.next;
return dummyNode.next;
}
Оценка сложности
Время: O(n), где n - число элементов в односвязном списке head