-
Notifications
You must be signed in to change notification settings - Fork 0
/
#26.cpp
88 lines (73 loc) · 1.32 KB
/
#26.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Node {
public:
int val;
Node* next;
Node(int v) {
val = v;
next = nullptr;
}
};
class LinkedList {
public:
Node* head;
LinkedList(vector<int> &v) {
Node* curr = new Node(v[0]);
head = curr;
for (int i = 1; i < v.size(); i++) {
Node* temp = new Node(v[i]);
curr->next = temp;
curr = temp;
}
}
void print() {
Node* curr = head;
while (curr != nullptr) {
cout << curr->val << ",";
curr = curr->next;
}
cout << endl;
}
};
Node* removeKthLast(Node* head, int k) {
Node* first = head;
Node* second = head;
Node* prev = nullptr;
// Iterate k times with first pointer
for (int i = 0; i < k; i++) {
first = first->next;
}
// Iterate both simultaneously until end
while (first != nullptr) {
first = first->next;
prev = second;
second = second->next;
}
// Second points to kth last item
if (prev == nullptr) {
return second->next;
} else {
prev->next = second->next;
return head;
}
}
int main() {
int k;
vector<int> v;
string in;
cin >> in;
k = stoi(in);
cin >> in;
istringstream ss(in);
string token;
while (getline(ss, token, ',')) {
v.push_back(stoi(token));
}
LinkedList *list = new LinkedList(v);
list->head = removeKthLast(list->head, k);
list->print();
}