鏈表節點包含前驅 prior、後繼 next 指針,支持雙向遍歷。本實現涵蓋創建、打印、插入、刪除、查找、文件讀寫持久化。
#define NULL 0
typedef struct student {
long num;
float score;
struct student *prior;
struct student *next;
} Student;
Student *head = NULL;
Student *create_linklist() {
Student *pTail = head, *pTemp;
int n, i;
printf("輸入節點數: "); scanf("%d", &n);
for (i = 0; i < n; i++) {
pTemp = (Student*)malloc(sizeof(Student));
printf("輸入學號 成績: "); scanf("%ld %f", &pTemp->num, &pTemp->score);
pTemp->next = NULL;
if (head == NULL) {
head = pTemp;
pTemp->prior = NULL;
} else {
pTail->next = pTemp;
pTemp->prior = pTail;
}
pTail = pTemp;
}
return head;
}
void print_list(Student *p) {
while (p != NULL) {
printf("學號:%ld 成績:%.2f\n", p->num, p->score);
p = p->next;
}
}
Student *insert_node(Student *head, int pos) {
Student *q = (Student*)malloc(sizeof(Student));
printf("輸入學號 成績: "); scanf("%ld %f", &q->num, &q->score);
Student *p = head;
int j = 0;
// 找到插入位置前一個節點
while (p != NULL && j < pos - 1) { p = p->next; j++; }
if (p == NULL) { printf("位置非法\n"); free(q); return head; }
// 插入邏輯
q->next = p->next;
q->prior = p;
if (p->next) p->next->prior = q;
p->next = q;
return head;
}
Student *delete_node(Student *head, int pos) {
Student *p = head;
int j = 0;
while (p != NULL && j < pos) { p = p->next; j++; }
if (p == NULL) { printf("位置非法\n"); return head; }
if (p->prior) p->prior->next = p->next;
else head = p->next; // 刪除頭節點
if (p->next) p->next->prior = p->prior;
free(p);
return head;
}
Student *search_node(Student *head, long num) {
Student *p = head;
while (p != NULL) {
if (p->num == num) return p;
p = p->next;
}
return NULL;
}
void save_to_file(Student *head, char *filename) {
FILE *fp = fopen(filename, "wb");
Student *p = head;
while (p) { fwrite(p, sizeof(Student), 1, fp); p = p->next; }
fclose(fp);
}
Student *load_from_file(char *filename) {
FILE *fp = fopen(filename, "rb");
if (!fp) return NULL;
Student *p1, *p2;
head = p1 = (Student*)malloc(sizeof(Student));
while (fread(p1, sizeof(Student), 1, fp) == 1) {
p2 = (Student*)malloc(sizeof(Student));
p1->next = p2;
p2->prior = p1;
p1 = p2;
}
p1->next = NULL; // 最後多分配一個需處理
fclose(fp);
return head;
}
void show_menu() {
printf("\n1.插入 2.刪除 3.查找 4.讀文件 5.存文件 6.打印 7.菜單 0.退出\n");
}
int main() {
char cmd;
show_menu();
while (scanf(" %c", &cmd) == 1) {
switch (cmd) {
case '1': insert_node(head, ...); break;
case '2': delete_node(head, ...); break;
case '3': search_node(head, ...); break;
case '4': head = load_from_file("data.dat"); break;
case '5': save_to_file(head, "data.dat"); break;
case '6': print_list(head); break;
case '7': show_menu(); break;
case '0': return 0;
}
}
return 0;
}
完整代碼可直接編譯運行,實現了雙向鏈表的基本管理功能。