Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

In k nút cuối danh sách liên kết ngược (Recursive) trong C

Bài toán

In k nút cuối danh sách liên kết theo thứ tự ngược, dùng đệ quy.

Ví dụ

List: 29→34→43→56→88
k=2 → Output: 88 56

In k nút cuối danh sách liên kết ngược (Recursive) trong C

Ý tưởng đệ quy

  • Đệ quy đến cuối list
  • Khi unwind (quay lại), tăng counter
  • Nếu counter ≤ k → in data

Mã nguồn C

#include <stdio.h>
#include <stdlib.h>

struct node { int data; struct node* next; };

struct node* get(int data) {
    struct node* n = malloc(sizeof(struct node));
    n->data = data; n->next = NULL; return n;
}

void lastval(struct node* head, int* count, int k) {
    if (!head) return;
    lastval(head->next, count, k);
    (*count)++;
    if (*count <= k) printf("%d ", head->data);
}

int main() {
    struct node* head = get(11);
    head->next = get(243);
    head->next->next = get(321);
    head->next->next->next = get(421);
    head->next->next->next->next = get(522);
    int k=2, count=0;
    printf("Last %d nodes: ", k);
    lastval(head, &count, k);
    return 0;
}

Kết quả

Last 2 nodes: 522 421