-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path876-middle-of-the-linked-list.cpp
More file actions
70 lines (64 loc) · 1.56 KB
/
Copy path876-middle-of-the-linked-list.cpp
File metadata and controls
70 lines (64 loc) · 1.56 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
#include <iostream>
#include <cstddef>
#include <vector>
using namespace std;
// https://leetcode.com/problems/middle-of-the-linked-list/
class Node {
public:
int data;
Node* next;
Node(int d) {
data = d;
next = NULL;
}
};
class Solution {
public:
Node* insert(Node* head, int data) {
if (head == NULL)
head = new Node(data);
else {
Node* tail {head};
while (tail && tail->next != NULL)
tail = tail->next;
tail->next = new Node(data);
}
return head;
}
void display(Node* head) {
Node* start = head;
while (start) {
cout << start->data << " ";
start = start->next;
}
}
// LeetCode method
// ListNode* middleNode(ListNode* head)
Node* middleNode(Node* head) {
vector<Node*> nodes;
Node* start {head};
while (start) {
nodes.push_back(start);
start = start->next;
}
size_t elements {nodes.size()};
return elements % 2 == 0 ? nodes[elements / 2] : nodes[(elements - 1) / 2];
}
};
int main() {
Node* head = NULL;
Solution mylist;
int T, data;
cin >> T;
while (T-- > 0) {
cin >> data;
head = mylist.insert(head, data);
}
mylist.display(head);
cout << '\n';
// middle node return
Node* head2 {mylist.middleNode(head)};
mylist.display(head2);
cout << '\n';
return 0;
}