Xóa một phần tử từ danh sách liên kết đôi trong C



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

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

#include 
#include struct node {
   int data;
   struct node *prev;
   struct node *next;
};struct node *head = NULL;
struct node *last = NULL;struct node *current = NULL;//hien thi list
void printList() {
   struct node *ptr = head;   printf("\n[head] <=>");
   //bat dau tu phan dau cua list
   while(ptr != NULL) {        
      printf(" %d <=>",ptr->data);
      ptr = ptr->next;
   }   printf(" [last]\n");
}void print_backward() {
   struct node *ptr = last;   printf("\n[last] <=>");
   //bat dau tu phan dau cua list
   while(ptr != NULL) {        
      printf(" %d <=>",ptr->data);
      ptr = ptr->prev;
   }   printf(" [head]\n");
}//tao danh sach lien ket
void insert(int data) {
   // cap phat bo nho cho node moi;
   struct node *link = (struct node*) malloc(sizeof(struct node));   link->data = data;
   link->prev = NULL;
   link->next = NULL;   // neu head la trong, tao list moi
   if(head==NULL) {
      head = link;
      return;
   }   current = head;
   
   // di chuyen toi phan cuoi list
   while(current->next!=NULL)
      current = current->next;
   
   // chen link vao phan cuoi cua list
   current->next = link;
   last = link;
   link->prev = current;
}
void remove_data(int data) {
   int pos = 0;
   struct node *pre_node;
    
   if(head==NULL) {
      printf("Danh sach lien ket chua duoc khoi tao");
      return;
   } 
    
   if(head->data == data) {
      if(head->next != NULL) {
         head->next->prev = NULL;
         head = head->next;
         return;
      }else {
         head = NULL;
         printf("Bay gio List la trong");
         return;
      }
   }else if(head->data != data && head->next == NULL) {
      printf("Khong tim thay %d trong list\n", data);
      return;
   }
           current = head;
   
   while(current->next != NULL && current->data != data) {
      pre_node = current;
      current = current->next;
   }           if(current->data == data) {
      pre_node->next = pre_node->next->next;
            
      if(pre_node->next != NULL) {          
         pre_node->next->prev = pre_node;
      }else
         last = pre_node;
                
      free(current);
   }else
      printf("Khong tim thay %d trong list.", data);}

int main() {
   insert(10);
   insert(20);
   insert(30);
   insert(1);
   insert(40);
   insert(56);    printList();
   remove_data(20);
   
   printList();
   print_backward();
   
   return 0;
}

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

Xóa phần tử trong danh sách liên kết đôi trong C
danh-sach-lien-ket-trong-c.jsp