Tạo danh sách liên kết đơn trong C



Bài tập C: Tạo danh sách liên kết đơn

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 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 tạo 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;//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(" [null]\n");
}//chen link tai vi tri dau tien
void insert(int data) {
   //tao mot link
   struct node *link = (struct node*) malloc(sizeof(struct node));   //link->key = key;
   link->data = data;   //tro link do toi first node cu
   link->next = head;   //tro first toi first node moi
   head = link;
}int main() {
   insert(10);
   insert(20);
   insert(30);
   insert(1);
   insert(40);
   insert(56);    printList();
   return 0;
}

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

Tạo danh sách liên kết đơn trong C
danh-sach-lien-ket-trong-c.jsp