In ngược danh sách liên kết không sửa đổi cấu trúc, chỉ duyệt một lần. Sử dụng ký tự carriage return (\r) để di chuyển con trỏ in ngược.
Ý tưởng
Đếm độ dài n. Duyệt danh sách, tại nút thứ j: in (n-j) khoảng trắng, in giá trị, in \r để về đầu dòng. Lặp lại cho nút tiếp theo. Kết quả in đè lên nhau tạo ra thứ tự ngược.
Ví dụ minh họa
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void printReverse(struct Node** head_ref, int n) {
int j = 0;
struct Node* current = *head_ref;
while (current != NULL) {
for (int i = 0; i < 2 * (n - j); i++)
cout << " ";
cout << current->data << "\r";
current = current->next;
j++;
}
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int printList(struct Node* head) {
int i = 0;
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
i++;
}
return i;
}
int main() {
struct Node* head = NULL;
push(&head, 2); push(&head, 7); push(&head, 3);
push(&head, 5); push(&head, 4); push(&head, 6);
printf("Danh sach goc:\n");
int n = printList(head);
printf("\nDanh sach nguoc:\n");
printReverse(&head, n);
return 0;
}
Kết quả
Danh sach goc: 6 4 5 3 7 2 Danh sach nguoc: 2 7 3 5 4 6