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



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

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

#include 
#include struct node {
   int data;
   struct node *next;
};struct node *head = NULL;
struct node *current = NULL;
struct node *prev = NULL;//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->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; 
}void display() {
   struct node *ptr = head;   printf("head] =>");
   //bat dau tu phan dau cua list
   while(ptr != NULL) {        
      printf(" %d =>",ptr->data);
      ptr = ptr->next;
   }   printf(" [null]\n");
}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 != 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;
   }
        
   
   
// prev = head;
   current = head;
   
   while(current->next != NULL && 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);}int main() {
   insert(10);
   insert(20);
   insert(30);
   insert(1);
   insert(40);
   insert(56);    printf("Truoc khi xoa: ");
   display();
   remove_data(30);
   printf("Sau khi xoa: ");
   display();
   
   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 đơn trong C
danh-sach-lien-ket-trong-c.jsp