forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middle_of_linkedlist.cpp
114 lines (89 loc) · 2.04 KB
/
middle_of_linkedlist.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
#include <bits/stdc++.h>
using namespace std;
//A linked list node
class node {
public:
int data;
node* next;
};
// Function for Inserting a node into beginning
int first(node* *head_f,int new_data)
{
node* new_node = new node();
new_node->data = new_data;
new_node->next = *head_f;
*head_f = new_node;
}
// Finction for Inserting a node after any node
int after(node* prev_node,int new_data)
{
// to check previous node is NULL or Not
if(prev_node == NULL){
cout << "Previous node cannot be Null";
}
node* new_node = new node();
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
// For Printing the entire linked list
int printlist(node *n)
{
while(n!=NULL){
cout << n->data << " ";
n = n->next;
}
}
// For deleting the linked list
int deletenode(node* head,int val){
node *temp = head;
while(temp->next->data!=val){
temp = temp->next;
}
node *todelete = temp->next;
temp->next = temp->next->next;
delete todelete;
}
// For finding the Middle of linkedlist
int middle(node* head){
node *slow = head;
node* fast = head;
while(fast!=NULL && fast->next!=NULL){
slow = slow->next;
fast = fast->next->next;
}
cout << slow->data;
}
// Main Function
int main(){
node* head = NULL;
node* second = NULL;
node* third = NULL;
// Making 3 Node
head = new node();
second = new node ();
third = new node ();
// Inserting data in 3 Node
head->data = 2;
head->next = second;
second->data = 3;
second->next = third;
third->data = 4;
third->next = NULL;
// Calling function for inserting at beginning.
first(&head,1);
// Calling function for inserting at end.
end(&third,5);
// Calling function for inserting after second Node.
//after(second,4);
// Calling function for delete given node.
//deletenode(head,3);
//Calling function for printing
cout << " The Linked List is " << endl;
printlist(head);
cout <<"\n\n";
// Caliing function for finding the middle
cout << "The Middle of Linked List is :" << endl;
middle(head);
return 0;
}