-
Notifications
You must be signed in to change notification settings - Fork 45
/
middle of a given linked list
81 lines (63 loc) · 1.18 KB
/
middle of a given linked list
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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class NodeOperation {
public:
void pushNode(class Node** head_ref, int data_val)
{
class Node* new_node = new Node();
new_node->data = data_val;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printNode(class Node* head)
{
while (head != NULL) {
cout << head->data << "->";
head = head->next;
}
cout << "NULL" << endl;
}
int getLen(class Node* head)
{
int len = 0;
class Node* temp = head;
while (temp) {
len++;
temp = temp->next;
}
return len;
}
void printMiddle(class Node* head)
{
if (head) {
// find length
int len = getLen(head);
class Node* temp = head;
// trvaers till we reached half of length
int midIdx = len / 2;
while (midIdx--) {
temp = temp->next;
}
// temp will be storing middle element
cout << "The middle element is [" << temp->data
<< "]" << endl;
}
}
};
// Driver Code
int main()
{
class Node* head = NULL;
class NodeOperation* temp = new NodeOperation();
for (int i = 5; i > 0; i--) {
temp->pushNode(&head, i);
temp->printNode(head);
temp->printMiddle(head);
}
return 0;
}