-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinsert_linked_list.cpp
136 lines (114 loc) · 1.93 KB
/
insert_linked_list.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
}*first=NULL;
void create(int a[],int n){
int i;
Node *t,*last;
first=new Node();
first->data = a[0];
first->next = NULL;
last=first;
for(i=1;i<n;i++){
t = new Node();
t->data = a[i];
t->next = NULL;
last->next=t;
last=t;
}
}
int count(Node *p){
int c=0;
while(p){
c++;
p=p->next;
}
return c;
}
int max(Node *p){
int m = -32768;
while(p){
if(p->data>m)
m = p->data;
p=p->next;
}
return m;
}
void display(Node *p){
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
Node * Lsearch(Node *p,int key){
while(p!=NULL){
if(key==p->data)
return p;
p=p->next;
}
return NULL;
}
Node * eff_Lsearch(Node *p,int key){
Node *q=NULL;
while(p!=NULL){
if(key==p->data){
q->next=p->next;
p->next=first;
first=p;
return p;
}
q=p;
p=p->next;
}
return NULL;
}
Node * Rsearch(Node *p,int key){
if(p==NULL)
return NULL;
if(key==p->data)
return p;
return Rsearch(p->next,key);
}
void insert(Node *p, int index,int x){
Node *t;
int i;
if(index<0 || index>count(p))
return;
t = new Node();
t->data = x;
if(index == 0){
t->next = first;
first = t;
}
else{
for(i=0;i<index-1;i++)
p=p->next;
t->next = p->next;
p->next = t;
}
}
int main(){
Node *temp;
// int a[] = {8,18,28};
// create(a,3);
insert(first,0,4);
insert(first,1,8);
insert(first,2,18);
insert(first,3,28);
// rec_display(first);
// cout<<"Count: "<<count(first);
// cout<<"Recursive Count: "<<rec_count(first);
// cout<<"Sum is: "<<add(first);
// cout<<"Maximum: "<<max(first);
// temp = Lsearch(first,18);
// temp = eff_Lsearch(first,18);
// if(temp)
// cout<<"Key found :"<<temp->data<<"\n";
// else
// cout<<"Key not found"<<"\n";
display(first);
return 0;
}