Cho một danh sách liên kết và một chỉ số. Viết hàm lấy nút thứ N trong danh sách liên kết.
Ví dụ:
Input
danh sách liên kết = 34 -> 4 -> 9 -> 1, n = 2
Output
9
Để đến nút thứ n, duyệt node bằng node và đếm chỉ số cho đến khi đạt vị trí thứ n.
Ví dụ minh họa
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int findNodeAt(Node* head, int index) {
Node* current = head;
int count = 0;
while (current != NULL) {
if (count == index)
return current->data;
count++;
current = current->next;
}
return -1; // Không tìm thấy
}
int main() {
Node* head = NULL;
insertNode(&head, 8);
insertNode(&head, 2);
insertNode(&head, 9);
insertNode(&head, 1);
insertNode(&head, 4);
int n = 2;
cout << "Phần tử tại chỉ số " << n << " là " << findNodeAt(head, 2);
return 0;
}
Kết quả
Phần tử tại chỉ số 2 là 9