-
Notifications
You must be signed in to change notification settings - Fork 0
/
LLinsertatmiddle.cpp
101 lines (85 loc) · 1.12 KB
/
LLinsertatmiddle.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
97
98
99
100
101
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *next;
node(int d)
{
data=d;
next=NULL;
}
};
void insertathead(node*&head,int data)
{
node*n=new node(data);
n->next=head;
head=n;
}
void insertatend(node*head,int data)
{
if(head==NULL)
{
insertathead(head,data);
}
node*tail=head;
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=new node(data);
}
int lenght(node*head)
{
int len=0;
while(head!=NULL)
{
head=head->next;
len=len+1;
}
return len;
}
void insertatmiddle(node*&head,int data,int p)
{
if(head==NULL)
{
insertathead(head,data);
}
if(p>lenght(head))
{
insertatend(head,data);
}
int jump=1;
node*prev=NULL;
node*cur=head;
while(jump<=p-1)
{
prev=cur;
cur=cur->next;
jump++;
}
node*n=new node(data);
n->next=prev->next;
prev->next=n;
}
void print(node*head)
{
while(head!=NULL)
{
cout<<head->data<<"->";
head=head->next;
}
}
int main()
{
node*head=NULL;
insertathead(head,5);
insertathead(head,6);
insertathead(head,7);
insertathead(head,2);
insertatend(head,9);
insertatmiddle(head,4,2);
print(head);
return 0;
}