-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab#05_Farhanulhaq__Task#2.cpp
More file actions
73 lines (65 loc) · 1.42 KB
/
Copy pathLab#05_Farhanulhaq__Task#2.cpp
File metadata and controls
73 lines (65 loc) · 1.42 KB
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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void addNode(Node** head, int data) {
Node* newNode = new Node{data, NULL};
if (*head == NULL) {
*head = newNode;
return;
}
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
Node* findMiddle(Node* head) {
if (head == NULL) return NULL;
Node* slow = head;
Node* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
bool isEmpty(Node* head) {
return head == NULL;
}
void printList(Node* head) {
if (isEmpty(head)) {
cout<<"The list is empty!"<<endl;
return;
}
while (head !=NULL)
{
cout<<head->data<<" ";
head=head->next;
}
cout << endl;
}
int main() {
Node* head=NULL;
if (isEmpty(head))
{
cout<<"The list is initially empty."<<endl;
}
addNode(&head,24);
addNode(&head,6);
addNode(&head, 90);
addNode(&head,19);
addNode(&head,78);
cout << "Linked List: ";
printList(head);
Node* middle = findMiddle(head);
if (middle != NULL) {
cout<<"Middle element: "<<middle->data<<endl;
} else
{
cout<<"The list is empty!"<<endl;
}
return 0;
}