-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_remove_nth_node.cpp
More file actions
47 lines (35 loc) · 1.06 KB
/
Copy path19_remove_nth_node.cpp
File metadata and controls
47 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string>
#include <iostream>
#include <sstream>
#include "parse_input.h"
// O(N)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// check if n >= 0, if head isn't nullprt (guaranteed in the task)
if (n == 0) return head;
ListNode* cur = head;
for (std::size_t i = 0; i < n; i++)
cur = cur->next;
// case of n = length, 0-th el. removal
if (!cur) return head->next;
ListNode* cur_m_n = head;
for( ; cur->next; cur=cur->next, cur_m_n=cur_m_n->next);
cur_m_n->next = cur_m_n->next->next;
return head;
}
};
int main(){
std::string line;
std::cout << "Space separated values of l: ";
std::getline(std::cin, line);
ListNode* l = str2List(line);
int n;
std::cout << "N: ";
std::cin >> n;
ListNode* l_res = Solution().removeNthFromEnd(l, n);
std::string answer;
List2str(l_res, answer);
std::cout << "After removal: " << answer << std::endl;
return 0;
}