forked from ravikartar/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 3
/
LinkedList_position_insertion
68 lines (65 loc) · 1.39 KB
/
LinkedList_position_insertion
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
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node *next;
node(int data) {
this->data = data;
next = NULL;
}
};
node *takeinput() { // take input using function
int data;
cin >> data;
node *head = NULL;
while (data != -1) {
node *newnode = new node(data);
if (head == NULL) {
head = newnode;
} else {
node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newnode;
}
cin >> data;
}
return head;
}
node *insertelement(node *head, int i, int data) { //extra elemnt insertion
node *newnode = new node(data);
int count = 0;
node *temp = head;
if (i == 0) {
newnode->next = head;
head = newnode;
return head;
}
while (temp != NULL && count < i - 1) {
temp = temp->next;
count++;
}
if (temp != NULL) {
node *a = temp->next;
temp->next = newnode;
newnode->next = a;
}
return head;
}
void print(node *head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
int main() {
node *head = takeinput();
print(head);
int i, data;
cin >> i >> data;
cout << endl;
head = insertelement(head, i, data);
print(head);
}