[AlgoExpert] Remove Kth Node From End

Remove Kth Node From End

  • Time : O(n)
  • Space : O(1)
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
#include <vector>
using namespace std;

class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value);
void addMany(vector<int> values);
vector<int> getNodesInArray();
};

void removeKthNodeFromEnd(LinkedList *head, int k) {
if(k <= 0) return;
LinkedList* runner = head;
while(k-- and runner) runner = runner->next;
if(!runner) {
if(k > 0) return;
head->value = head->next->value;
} else {
while(runner->next) {
head = head->next;
runner = runner->next;
}
}

head->next = head->next->next;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/14/PS/AlgoExpert/remove-kth-node-from-end/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.