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 theo thứ tự ngược (Iterative) trong C

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)

In k nút cuối danh sách liên kết theo thứ tự ngược (Iterative) trong C

Phương pháp dùng mảng (giả lập stack)

  1. Đếm tổng số nút (count)
  2. Tạo mảng size count, lưu data theo thứ tự ngược
  3. 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