forked from namishkhanna/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked List.cpp
155 lines (133 loc) · 2.28 KB
/
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
node *next;
};
node *top=NULL;
void insert_front (int idata)
{
node* temp = new node;
temp->data = idata;
temp->next=NULL;
if(top==NULL)
{
top=temp;
}
else
{
temp->next = top;
top = temp;
}
}
void display() {
node* ptr;
ptr = top;
while (ptr != NULL)
{
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
void insert_end(int idata)
{
node *temp = new node;
temp->data = idata;
temp->next =NULL;
node *ptr =top;
while(ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = temp;
}
void count()
{
int count = 0;
node *ptr;
ptr = top;
while(ptr != NULL)
{
count = count + 1;
ptr = ptr->next;
}
cout<<"\n"<<"Total Length is : "<<count;
}
void search(int data)
{
int pos = 1;
node *ptr;
ptr = top;
while(ptr != NULL && ptr->data != data)
{
pos = pos + 1;
ptr = ptr->next;
}
if(ptr != NULL)
cout<<"\n"<<"Found at : "<<pos<<" and memory address"<<&ptr;
else
cout<<"\n"<<"Not Found!!!";
}
int delete_front()
{
node* ptr = top;
if(ptr==NULL)
return -1;
top=ptr->next;
delete ptr;
}
node* delete_last()
{
if (top== NULL)
return NULL;
if (top->next == NULL)
{
delete top;
return NULL;
}
node* second_last = top;
while (second_last->next->next != NULL)
second_last = second_last->next;
second_last->next = NULL;
return top;
}
int delete_at(int pos)
{
int i=1;
node *ptr = top;
node *prev;
while(i !=pos )
{
if(ptr->next==NULL)
{
cout<<"not found";
}
prev = ptr;
ptr = ptr->next;
i++;
}
prev->next = ptr->next;
delete ptr;
cout<<"\nSuccesfully Deleted at Position : "<<pos<<"\n ";
}
int main() {
insert_front(3);
insert_front(1);
insert_front(7);
insert_front(2);
insert_end(13);
insert_front(9);
insert_end(11);
//delete_first();
cout<<"The linked list is: ";
display();
count();
//delete_at(3);
//search(7);
delete_last();
cout<<"\nThe linked list is: ";
display();
return 0;
}