Hiển thị danh sách liên kết vòng theo chiều đảo ngược trong C



Bài tập C: Hiển thị danh sách liên kết vòng theo chiều đảo ngược

Bài tập C này giúp bạn làm quen dần với cách tạo danh sách liên kết vòng và cách hiển thị danh sách liên kết vòng trong C. Để giải bài tập này, mình sử dụng cấu trúc struct trong C.

Chương trình C

Dưới đây là chương trình C để giải bài tập hiển thị danh sách liên kết vòng theo chiều đảo ngược trong C:

#include 
#include struct node {
   int data;
   struct node *next;
};struct node *head = NULL;
struct node *current = NULL;//chen link tai vi tri dau tien
void insert(int data) {
   // cap phat bo nho cho node moi;
   struct node *link = (struct node*) malloc(sizeof(struct node));   link->data = data;
   link->next = NULL;   // neu head la trong, tao list moi
   if(head==NULL) {
      head = link;
      head->next = link;
      return;
   }   current = head;
   
   // di chuyen toi phan cuoi list
   while(current->next != head)
      current = current->next;
   
   // chen link vao phan cuoi cua list
   current->next = link;
   
   // lien ket last node voi head
   link->next = head;
   
}//hien thi list
void reverse_print(struct node *list) {
   if(list->next == head) {
      printf(" %d =>",list->data);
      return;
   }
   reverse_print(list->next);
   printf(" %d =>",list->data);
   
}int main() {
   insert(10);
   insert(20);
   insert(30);
   insert(1);
   insert(40);
   insert(56); 
   
   reverse_print(head);
   printf(" [head]\n");
   
   return 0;
}

Biên dịch chương trình C trên sẽ cho kết quả:

Hiển thị danh sách liên kết vòng trong C
danh-sach-lien-ket-trong-c.jsp