-
Notifications
You must be signed in to change notification settings - Fork 1
/
Inserting_a_node_before_head.cpp
71 lines (65 loc) · 1.22 KB
/
Inserting_a_node_before_head.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
#include<iostream>
using namespace std;
struct node{
int data;
struct node *next;
};
int main(){
int response;
cout<<"Type '1' to create a node\n";
cin>>response;
struct node *head, *p;
if(response == 1){
head = new node();
cout<<"Enter Head Data:";
cin>>head->data;
head->next = NULL;
p = head;
}
else{
cout<<"You have not typed 1";
return 0;
}
int n;
cout<<"The data in Head is:"<<head->data;
cout<<"\nNumber of nodes you want to insert after head (n) =";
cin>>n;
int i=0;
while(i<n){
struct node *q;
q = new node();
cout<<"Enter the data of node "<<i+1<<":";
cin>>q->data;
p->next = q;
q->next = NULL;
p = p->next;
i++;
}
struct node *r;
r = head;
cout<<"Data of all nodes are respectively: ";
while(r != NULL){
cout<<r->data<<" ";
r = r->next;
}
cout<<"\n";
int response2;
cout<<"Type '1' if you want to insert a node before head\n";
cin>>response2;
if(response2 == 1){
struct node *t;
t = new node();
cout<<"Enter the data in the new node:";
cin>>t->data;
t->next = head;
head = t;
}
struct node *u;
u = head;
cout<<"Data of all nodes after inserting new node are respectively: ";
while(u != NULL){
cout<<u->data<<" ";
u = u->next;
}
return 0;
}