-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiddle_LL.C++
84 lines (73 loc) · 1.36 KB
/
Middle_LL.C++
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
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node(int val){
data = val;
next = NULL;
}
};
node *add(node *head, int val){
node *temp = new node(val);
if(head == NULL){
head = temp;
return head;
}
node *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = temp;
return head;
}
void print(node *head){
node *temp = head;
while(temp != NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
//Middle of the linked list
int middle(node *head){
if(head == NULL )
return -1;
if(head->next == NULL)
return head->data;
int count =0;
node*temp =head;
while(temp!=NULL){
count++;
temp =temp->next;
}
int half = (count)/2;
temp = head;
while(half > 0){
temp = temp->next;
half--;
}
return temp->data;
}
//--O(N)
int mid(node *head){
if(head == NULL)
return -1;
node *slow = head;
node *fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
return slow->data;
}
int main(){
node *head = NULL;
int n,v;
cin>>n;
for(int i=0;i<n;i++){
cin>>v;
head = add(head,v);
}
cout<<middle(head)<<endl;
}