-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionAndDeletionAtAnyIndex.cpp
More file actions
80 lines (77 loc) · 1.4 KB
/
insertionAndDeletionAtAnyIndex.cpp
File metadata and controls
80 lines (77 loc) · 1.4 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
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
Node* next;
int data;
Node(int x) {
next = nullptr;
data = x;
}
};
void printList(Node* head) {
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
//index=2;
//2->4->5->9->10
Node* insertNode(Node** head, int data , int index) {
Node * new_node = new Node(data);
if (index == 0) {
new_node->next = *head;
*head = new_node;
}
else {
Node* cur = *head;
Node*prev = cur;
while (index != 0 && cur != nullptr) {
prev = cur;
cur = cur->next;
index--;
}
prev->next = new_node;
new_node->next = cur;
}
return *head;
}
int deleteNode(Node** head, int index) {
if (*head == nullptr) {
return -1;
}
if (index == 0) {
int data = ((*head)->data);
Node*nex = ((*head)->next);
*head = nex;
return data;
}
else {
Node*cur = *head;
Node*prev = cur;
while (index != 0 && cur != nullptr) {
prev = cur;
cur = cur->next;
index--;
}
if (cur == nullptr) {
return -1;
}
prev->next = cur->next;
return cur->data;
}
}
int main() {
Node* head = nullptr;
insertNode(&head, 11, 0);
insertNode(&head, 17, 0);
insertNode(&head, 4, 0);
insertNode(&head, 8, 4);
printList(head);
deleteNode(&head, 2);
deleteNode(&head, 0);
deleteNode(&head, 1);
printList(head);
return 0;
}