forked from IOSD/Algo
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlinked.cpp
81 lines (70 loc) · 1.41 KB
/
linked.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
72
73
74
75
76
77
78
79
80
81
//linked_list_insertion
//conmplexity : O(n)
#include <iostream.h>
#include <conio.h>
struct link
{ int n;
link *next; //self referential pointer
}*h,*ptr,*tmp;
void main()
{ clrscr();
int choice,i=0;
cout<<"Linked list:\n";
cout<<"Add elements\n";
h=new link; //dynamic initialisation of element in linked list
h->next=NULL;
ptr=h;
for(;i<4;i++)
{ cout<<"Enter no.:\n";
cin>>ptr->n;
if(i<4)
{ ptr->next=new link; //dynamic initialisation of element in linked list
ptr->next->next=NULL;
}
ptr=ptr->next;
}
ptr=h;
for(i=0;i<4;i++)
{ cout<<ptr->n;
ptr=ptr->next;
cout<<"\t";
}
cout<<"\n\nWHERE TO ADD MORE No: ";
cout<<"\n1.BEGINNING\n2.END\n";
cout<<"Enter your choice :";
cin>>choice;
tmp=new link;
tmp->next=NULL;
cout<<"ENTER THE No.: ";
cin>>tmp->n;
if(choice==1) //add element in beginning
{ ptr=h;
tmp->next=ptr;
ptr=tmp;
cout<<"THIS IS AT THE BEGINGING: \n" ;
for(i=0;i<5;i++)
{ cout<<ptr->n;
cout<<"\t";
ptr=ptr->next;
}
}
else if(choice==2) //add element in the end of list
{
ptr=h;
cout<<"Insertion at the end: \n";
for(i=0;i<5;i++)
{ if(ptr->next==NULL)
{ ptr->next=tmp;
tmp->next=NULL;
}
ptr=ptr->next;
}
ptr=h;
for(i=0;i<5;i++)
{ cout<<ptr->n<<"\t";
ptr=ptr->next;
}
}
else
cout<<"WRONG CHOICE\n";
}