forked from Vaani-pathariya/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveNthNode.cpp
52 lines (52 loc) · 958 Bytes
/
RemoveNthNode.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
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node * next;
node(int val){
data=val;
next=NULL;
}
};
void print(node * root){
while (root!=NULL)
{
cout<<root->data<<" ";
root=root->next;
}
}
node * removeNth(node * root ,int n){
node * temp = root;
int len=0;
while (temp!=NULL)
{
len++;
temp=temp->next;
}
node * iter=root;
int count=0;
if (len==n && n==1)
return NULL;
if (len==n)
return root->next;
while (count<(len-n)-1)
{
iter=iter->next;
count++;
}
iter->next=iter->next->next;
return root;
}
int main(){
node * head = new node(1);
head->next=new node(2);
head->next->next=new node(3);
head->next->next->next=new node(4);
head->next->next->next->next=new node(5);
int n;
cin>>n;
removeNth(head,n);
print(head);
return 0;
}