/
DeC2018
/
0019
Обзор
Документация
Войти
/
DeC2018
/
0019
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.cpp
64 строки
1 KB
Den
create main.cpp
22 дек 2024, 23:33
22 дек 2024, 23:33
3535fa1
Код
Авторство
О чём код?
#include <iostream> struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* slow = dummy; ListNode* fast = dummy; for (int i = 0; i <= n; i++) { fast = fast->next; } while (fast != nullptr) { slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return dummy->next; } }; int main() { // Test the removeNthFromEnd function ListNode* head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(3); head->next->next->next = new ListNode(4); head->next->next->next->next = new ListNode(5); Solution solution; ListNode* newHead = solution.removeNthFromEnd(head, 2); // Output the modified linked list ListNode* current = newHead; while (current != nullptr) { std::cout << current->val << " "; current = current->next; } return 0; }