-
Notifications
You must be signed in to change notification settings - Fork 0
/
54.LinkedList_Operations_P2.cpp
62 lines (53 loc) · 1.11 KB
/
54.LinkedList_Operations_P2.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
/*
creating linked list using insert operation
*/
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
}*first;
void insert(node* p, int x, int pos){
if(pos!=0){
for(int i=0;i<pos-1;i++){
if(p==NULL){
cout<<"Cant insert "<<x<<" at "<<pos<<" linked list only has "<<i<<" elements. ENDING"<<endl;
return;
}
else{
p = p->next;
}
}
node* temp = new node;
temp->data = x;
temp->next = p->next;
p->next = temp;
}
else{
//assuming it is being inserted for the very first time
first->data = x;
}
}
void create(node* p){
int num;
cout<<"Enter number of elemets in linked list: ";
cin>>num;
int x;
for(int i=0;i<num;i++){
cout<<"Enter "<<i<<" element: ";
cin>>x;
insert(p,x,i);
}
cout<<"Completed!\n";
}
void display(node* p){
while(p!=NULL){
cout<<p->data<<" ";
p = p->next;
}
}
int main(){
first = new node;
create(first);
display(first);
}