Danh sách liên kết (Linked List) dùng cấp phát bộ nhớ động, co giãn linh hoạt. Mỗi nút (node) gồm 2 phần: Dữ liệu và Con trỏ next.
Các loại danh sách liên kết
- Đơn (Singly)
- Kép (Doubly)
- Đơn vòng (Circular singly)
- Kép vòng (Circular doubly)
Chương trình C: Danh sách đơn lưu thông tin xe (model, color, year)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char model[10], color[10];
int year;
struct node *next;
};
struct node *temp, *head;
void display(struct node *head) {
temp = head;
while (temp != NULL) {
if (temp->year > 2010 && strcmp("yellow", temp->color) == 0)
printf(" %s \t\t %s \t\t %d", temp->model, temp->color, temp->year);
temp = temp->next;
printf("\n");
}
}
int main() {
int n;
char option, enter;
head = (struct node *)malloc(sizeof(struct node));
temp = head;
do {
printf("\nNhập model xe: "); scanf("%s", temp->model);
printf("Nhập màu xe: "); scanf("%s", temp->color);
printf("Nhập năm sản xuất: "); scanf("%d", &temp->year);
printf("\nTiếp tục? Y/N: ");
scanf("%c", &enter); // đọc ký tự newline
scanf("%c", &option);
if (option != 'N') {
temp->next = (struct node *)malloc(sizeof(struct node));
temp = temp->next;
} else {
temp->next = NULL;
}
} while (option != 'N');
display(head);
return 0;
}
Kết quả mẫu
Nhập model: I20 Màu: white Năm: 2016 Tiếp tục? Y Nhập model: verna Màu: red Năm: 2018 Tiếp tục? Y Nhập model: creta Màu: Maroon Năm: 2010 Tiếp tục? N (Không in gì vì không có xe vàng năm > 2010)