Xóa một phần tử từ danh sách liên kết vòng trong C



Bài tập C: Xóa một phần tử từ danh sách liên kết vòng

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 xóa một phần tử từ 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 xóa một phần tử từ danh sách liên kết vòng trong C:

#include 
#include struct node {
   int data;
   struct node *next;
};struct node *head = NULL;
struct node *current = NULL;
struct node *prev = 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;
   
}void remove_data(int data) {
   int pos = 0;
   
   if(head==NULL) {
      printf("Danh sach lien ket chua duoc khoi tao");
      return;
   } 
    
   if(head->data == data) {
      if(head->next != head) {
         current = head;
         while(current->next!=head) {
            current = current->next;
         }
         current->next = head->next;
         head = head->next;
         return;
      }else {
         head = NULL;
         printf("List la trong\n");
         exit(0);
      }
   }else if(head->data != data && head->next == NULL) {
      printf("Khong tim thay %d trong list\n", data);
      return;
   }
           current = head;
   
   while(current->next != head && current->data != data) {
      prev = current;
      current = current->next;
   }           if(current->data == data) {
      prev->next = prev->next->next;
      free(current);
   }else
      printf("Khong tim thay %d trong list.", data);
}//hien thi list
void printList() {
   struct node *ptr = head;   printf("\n[head] =>");
   
   //bat dau tu phan dau cua list
   while(ptr->next != head) {        
      printf(" %d =>",ptr->data);
      ptr = ptr->next;
   }
   
   printf(" %d =>",ptr->data);
   printf(" [head]\n");
}int main() {
   insert(10);
   insert(20);
   insert(30);
   insert(1);
   insert(40);
   insert(56); 
   
   printf("List ban dau: ");
   printList();
   remove_data(1);
   
   printf("List sau khi xoa: ");
   printList();
    
   return 0;
}

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

Xóa một phần tử từ danh sách liên kết vòng trong C
danh-sach-lien-ket-trong-c.jsp