-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeletion.cpp
More file actions
67 lines (61 loc) · 1.22 KB
/
deletion.cpp
File metadata and controls
67 lines (61 loc) · 1.22 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data){
this->data = data;
next = NULL;
}
};
int length(Node* head){
if(head){
return 0;
}
return 1 + length(head->next);
}
Node* removeNthFromEnd(Node* head,int n){
int len = length(head);
int x = len-n;
Node* temp = head;
while(x>0){
temp = temp->next;
x--;
}
Node* next = temp->next->next;
free(temp->next);
temp->next = next;
return head;
}
void append(Node** head_ref,int data){
Node* newNode = new Node(data);
Node* head = *head_ref;
if(head == NULL){
*head_ref = newNode;
}else{
while(head->next){
head = head->next;
}
head->next = newNode;
}
return;
}
void printList(Node* head){
while(head){
cout<<head->data<< ' ';
head = head->next;
}
cout<<endl;
}
int main(){
Node* head = NULL;
append(&head,1);
append(&head,2);
append(&head,3);
append(&head,4);
append(&head,5);
printList(head);
Node* res = removeNthFromEnd(head,2);
printList(res);
}