-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDay-026.cpp
72 lines (68 loc) · 1.67 KB
/
Day-026.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
/*
* Given a singly linked list and an integer k, remove the kth last element from the list.
* k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.
*/
/*
* Idea is to use two pointer Here & Tortoise , where Tortoise will first move K+1 node ahead and then both will move with
* at once , when Tortoise pointer hit null then we have to delete the Here+1 node
*/
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
void print(Node*root){
Node*temp= root;
while(temp!=NULL){
cout<<temp->data<<" ";
temp= temp->next;
}
puts("");
return;
}
Node* get_node(int value){
Node *temp = new Node();
temp->next = NULL;
temp->data = value;
return temp;
}
Node* add(Node *root , int value){
if(root==NULL){
return get_node(value);
}else{
root->next = add(root->next , value);
return root;
}
}
void remove(Node*root , int k ){
Node* here = root , *tor = root; // tortoise & here
++k;
while(k--){
tor = tor->next;
}
while(tor!=NULL){
tor = tor->next;
here = here->next;
}
here->next = here->next->next;
return;
}
int main(int argc , char *argv[]){
// write you code here
Node *root = NULL;
root = add(root , 10);
root = add(root , 20);
root = add(root , 30);
root = add(root , 40);
root = add(root , 50);
root = add(root , 60);
print(root);
remove(root , 2); /// will delete 50
print(root);
remove(root,1);
print(root);
return 0;
}