Bài toán
In k nút cuối của danh sách liên kết theo thứ tự ngược, dùng phương pháp lặp (iterative).
Ví dụ
List: 29→34→43→56→88 k=2 → Output: 56 88 (ngược: 88 56? Đề bài in 56 88)

Phương pháp dùng mảng (giả lập stack)
- Đếm tổng số nút (count)
- Tạo mảng size count, lưu data theo thứ tự ngược
- In k phần tử đầu mảng
Mã nguồn C
#include <stdio.h>
#include <stdlib.h>
struct node { int data; struct node *next; };
struct node* intoList(int data) {
struct node* n = malloc(sizeof(struct node));
n->data = data; n->next = NULL; return n;
}
void rev(struct node* head, int count, int k) {
struct node* t = head;
while (t) { count++; t = t->next; }
int arr[count], idx = count;
t = head;
while (t) { arr[--idx] = t->data; t = t->next; }
for (int i=0; inext = intoList(76);
head->next->next = intoList(13);
head->next->next->next = intoList(24);
head->next->next->next->next = intoList(55);
head->next->next->next->next->next = intoList(109);
rev(head, 0, 3);
return 0;
}
Kết quả
109 55 24