forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked list insertion insertion at head,last,midle.cpp
96 lines (86 loc) · 1.49 KB
/
linked list insertion insertion at head,last,midle.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
using namespace std;
class node{
public:
int data;
node *next;
node(int d){
data =d;
next=NULL;
}
};
//insert at beginning
void insert_at_head(node *&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node *n=new node(data);
n->next=head;
head=n;
}
//insert at last
void insert_at_tail(node *&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node *tail=head;
while(tail->next!=NULL){
tail=tail->next;
}
tail->next=new node(data);
return;
}
//length of linked list
int length(node *head){
int cnt=0;
while(head!=NULL){
cnt++;
head=head->next;
}
return cnt;
}
//insert at given position
void insert_in_middle(node *&head,int data,int p){
//corner case
if(head==NULL or p==0){
insert_at_head(head,data);
}
else if(p>length(head)){
insert_at_tail(head,data);
}
else{
//take p-1 jumps
int jump=1;
node *temp=head;
while(jump<=p-1){
temp=temp->next;
jump++;
}
//create a new node
node *n =new node(data);
n->next=temp->next;
temp->next=n;
}
}
//display the list
void print(node *head){
while(head!=NULL){
cout<<head->data;
head=head->next;
}
}
int main(){
node *head=NULL;
insert_at_head(head,5);
insert_at_head(head,4);
insert_at_head(head,2);
insert_at_head(head,1);
insert_at_head(head,0);
print(head);
cout<<endl;
insert_at_tail(head,6);
insert_in_middle(head,3,3);
print(head);
}