-
Notifications
You must be signed in to change notification settings - Fork 2
/
Linked List.cpp
140 lines (118 loc) · 2.38 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
/* -------------------------------- */
/* Name: MD. Khairul Basar */
/* Institute: HSTU */
/* Dept: CSE */
/* Email: khairul.basar93@gmail.com */
/* -------------------------------- */
#include <bits/stdc++.h>
/* all header files included */
using namespace std;
struct linked_list
{
int data;
struct linked_list *next;
};
typedef struct linked_list node; /* node type defined */
void first_node(node *head, int n)
{
head->data=n;
head->next=NULL;
}
void add_node(node *head, int n)
{
node *new_node= new node;
new_node->data=n;
new_node->next=NULL;
node *occur=head;
while(occur)
{
if(occur->next==NULL)
{
occur->next=new_node;
return;
}
occur=occur->next;
}
}
void insert_front(node **head, int n)
{
node *new_node= new node;
new_node->data=n;
new_node->next=*head;
*head=new_node;
}
node* search_node(node *head, int n)
{
node *occur=head;
while(occur)
{
if(occur->data==n)
return occur;
occur=occur->next;
}
cout<<"Node "<<n<<" not found in the list.\n\n";
}
bool delete_node(node **head, node *ptrdel)
{
node *occur=*head;
if(ptrdel==*head)
{
*head=occur->next;
delete ptrdel;
return true;
}
while(occur)
{
if(occur->next==ptrdel)
{
occur->next=ptrdel->next;
delete ptrdel;
return true;
}
occur=occur->next;
}
return false;
}
void delete_linked_list(node **head)
{
node *temp_node;
while(*head)
{
temp_node=*head;
*head=temp_node->next;
delete temp_node;
}
cout<<"Linked List Deleted!\n\n";
}
void display(node *head)
{
node *lists=head;
while(lists)
{
cout<<lists->data<<" ";
lists=lists->next;
}
cout<<endl<<endl;
}
int main()
{
int numdel;
node *ptrdel;
node *new_head;
node *head= new node;
first_node(head,10);
display(head);
add_node(head,20);
display(head);
add_node(head,30);
display(head);
insert_front(&head,5);
display(head);
numdel=20;
ptrdel=search_node(head,numdel);
if(delete_node(&head,ptrdel))
cout<<"Node "<<numdel<<" deleted!\n\n";
display(head);
delete_linked_list(&head);
return 0;
}