數據結構定義
struct Employee {
int id;
char name[20];
int age;
struct Employee *next;
};
核心功能函數
1. 創建鏈表(頭插法,輸入 3 筆)
struct Employee* create() {
struct Employee *head = NULL, *p;
for (int i = 0; i < 3; i++) {
p = malloc(sizeof(struct Employee));
p->id = i;
gets(p->name); // 注意:gets 不安全,建議用 fgets
p->age = 21 + i;
p->next = head;
head = p;
}
return head;
}
2. 遍歷輸出
void output(struct Employee *p) {
while (p) {
printf("工號:%d 姓名:%s 年齡:%d\n", p->id, p->name, p->age);
p = p->next;
}
}
3. 選擇排序(按年齡升序,交換節點數據域)
struct Employee* sort(struct Employee *head) {
for (struct Employee *i = head; i; i = i->next) {
struct Employee *min = i;
for (struct Employee *j = i->next; j; j = j->next)
if (j->age < min->age) min = j;
// 交換數據域
int t_id = i->id, t_age = i->age; char t_name[20];
strcpy(t_name, i->name);
i->id = min->id; i->age = min->age; strcpy(i->name, min->name);
min->id = t_id; min->age = t_age; strcpy(min->name, t_name);
}
return head;
}
4. 有序插入(按年齡)
struct Employee* insert(struct Employee *head, struct Employee *node) {
struct Employee *prev = NULL, *cur = head;
while (cur && cur->age < node->age) {
prev = cur; cur = cur->next;
}
if (!prev) { // 插入頭部
node->next = head; return node;
}
prev->next = node; node->next = cur;
return head;
}
5. 按姓名刪除
struct Employee* delete(struct Employee *head, char *name) {
struct Employee *prev = NULL, *cur = head;
while (cur && strcmp(cur->name, name)) {
prev = cur; cur = cur->next;
}
if (!cur) return head; // 未找到
if (!prev) head = cur->next; // 刪除頭節點
else prev->next = cur->next;
free(cur);
return head;
}
主函數測試流程
int main() {
struct Employee *list = create();
output(list);
list = sort(list); output(list);
struct Employee e = {3, "John", 24};
list = insert(list, &e); output(list);
list = delete(list, "John"); output(list);
return 0;
}
代碼規範建議
- 替換
gets → fgets(name, sizeof(name), stdin) 並去除換行符。
- 排序交換數據域適用於小結構體;大結構體建議調整指針交換節點。
- 增加錯誤碼返回,避免直接
exit 導致資源洩漏。