以下是使用 C 语言实现的链表练习程序: ```c #include <stdio.h> #include <stdlib.h> typedef struct { int value; } datastruct_t; typedef struct _list { datastruct_t* pstdata; struct _list* nextptr; } listnode_t; // 创建新节点 listnode_t* createNode(int value) { listnode_t* newNode = (listnode_t*)malloc(sizeof(listnode_t)); if (newNode == NULL) { printf("Memory allocation failed!\n"); return NULL; } newNode->pstdata = (datastruct_t*)malloc(sizeof(datastruct_t)); if (newNode->pstdata == NULL) { printf("Memory allocation failed!\n"); free(newNode); return NULL; } newNode->pstdata->value = value; newNode->nextptr = NULL; return newNode; } // 按数字从大到小顺序插入节点 void insertNode(listnode_t head, int value) { listnode_t* newNode = createNode(value); if (*head == NULL || value > (*head)->pstdata->value) { newNode->nextptr = *head; *head = newNode; return; } listnode_t* current = *head; while (current->nextptr!= NULL && current->nextptr->pstdata->value > value) { current = current->nextptr; } newNode->nextptr = current->nextptr; current->nextptr = newNode; } // 删除指定值的节点 void deleteNode(listnode_t head, int value) { listnode_t* temp = *head; listnode_t* prev = NULL; if (temp!= NULL && temp->pstdata->value == value) { *head = temp->nextptr; free(temp->pstdata); free(temp); return; } while (temp!= NULL && temp->pstdata->value!= value) { prev = temp; temp = temp->nextptr; } if (temp == NULL) { printf("Element not found in the list.\n"); return; } prev->nextptr = temp->nextptr; free(temp->pstdata); free(temp); } // 打印链表 void printList(listnode_t* head) { listnode_t* current = head; printf("List: "); while (current!= NULL) { printf("%d ", current->pstdata->value); current = current->nextptr; } printf("\n"); } int main() { listnode_t* head = NULL; int choice; printf("please enter your choice:\n"); printf("1 is to insert an element to the list.\n"); printf("2 is to delete an element from the list.\n"); printf("3 is to quit.\n"); printf("? "); scanf("%d", &choice); while (choice!= 3) { if (choice == 1) { int value; printf("enter an int to insert: "); scanf("%d", &value); insertNode(&head, value); } else if (choice == 2) { int value; printf("enter an int to be deleted: "); scanf("%d", &value); deleteNode(&head, value); } printList(head); printf("? "); scanf("%d", &choice); } // 释放链表内存 listnode_t* temp; while (head!= NULL) { temp = head; head = head->nextptr; free(temp->pstdata); free(temp); } return 0; } ``` [2024-08-26 06:28:23 | AI写代码神器 | 939点数解答]