Hướng giải của Phần tử ở giữa
Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.
Lời giải
Dùng kỹ thuật hai con trỏ (slow/fast): slow di chuyển 1 bước, fast di chuyển 2 bước. Khi fast kết thúc, slow ở vị trí middle-right.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
int main() {
int n; cin >> n;
Node *head = nullptr, *tail = nullptr;
for (int i = 0; i < n; ++i) {
int x; cin >> x;
Node* node = new Node(x);
if (!head) head = tail = node;
else tail->next = node, tail = node;
}
Node *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
cout << slow->data;
}
class Node:
def __init__(self, val):
self.data = val
self.next = None
n = int(input())
a = list(map(int, input().split()))
head = tail = None
for val in a:
node = Node(val)
if head is None: head = tail = node
else: tail.next = node; tail = node
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
print(slow.data)
Nhận xét