-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertAtMiddle.cpp
80 lines (79 loc) · 1.84 KB
/
insertAtMiddle.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
#include<iostream>
using namespace std;
class node{
public:
int data;
node*next;
node(int d){
data=d;
node*next=NULL;
}
};
int length(node*head){
int len=0;
while(head!=NULL){
len+=1;
}
return len;
}
void insertAtTail(node*&head,int data){
if(head=NULL){
head= new node(data);
return;
}
else{
node*tail= head;
while(tail->next!=NULL){
tail= tail->next;
}
return;
}
}
void insertAtFirst(node*&head, int data){
node*n = new node(data);
n->next= head;
head=n;
}
void insertAtMiddle(node*&head, int data, int p){
if(head==NULL or p==0){ //Why Not to create a function for this which would be very easy to insert
insertAtFirst(head,data); //at the first node. :D
}
//If Postition is given which is higher than the length of the LinkedList we will insert into the end. Obviously.:)
else if(p>length(head)){
insertAtTail(head, data);
}
//Insert at the Middle.
else{
//First we need to compute from the Jump 1 to Jump P-1.
//Because if our position=3 then we need to insert this element after 2nd node.
int jump=1;
node*temp=head;
while(jump<=p-1){
temp= temp->next;
jump+=1;
}
// Now after loop is end temp is at right position
//We will create a new Node which contains the new element we want to insert
// And since every node contains a int data + next node so the node* of this newly created node will
// point to the temp*next node which was pointing earlier. Its simple.
node*n= new node(data);
temp->next= n;
n->next= temp->next;
}
}
void print(node*head){
while(head!=NULL){
cout<<head->data<<"->";
head=head->next;
}
cout<<endl;
}
int main()
{
node*head=NULL;
insertAtFirst(head,1);
insertAtFirst(head,2);
insertAtTail(head,4);
insertAtMiddle(head,3,2);
print(head);
}