酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

使用下面的数据结构,编写一个链表练习程序。 typedef struct{ int value; }datastruct_t; typedef struct _list{ datastruct_t* pstdata; struct _list* nextptr; }listnode_t; 2. 实现按数字从大到小顺序插入数据insertnode,删除数据deletenode,打印数据 printlist函数及主程序。 3. 程序开始显示如下提示信息: please enter your choice: 1 is to insert an element to the list. 2 is to delete an element from the list. 3 is to quit. 4. 使用‘?’提示输入选择数字。 5. 在输入字符‘1’后,程序提示输入待插入整数:"enterainttoinsert:" 6. 在输入字符‘2’后,程序提示输入待删除整数:"enterainttobedeleted:" 7. 在输入字符‘3’后,程序退出

以下是使用 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; // 打印链表函数 void printlist(listnode_t* head) { listnode_t* current = head; while (current!= NULL) { printf("%d ", current->pstdata->value); current = current->nextptr; } printf("\n"); } // 按数字从大到小顺序插入节点 listnode_t* insertnode(listnode_t* head, int value) { listnode_t* newNode = (listnode_t*)malloc(sizeof(listnode_t)); newNode->pstdata = (datastruct_t*)malloc(sizeof(datastruct_t)); newNode->pstdata->value = value; listnode_t* current = head; listnode_t* prev = NULL; while (current!= NULL && current->pstdata->value > value) { prev = current; current = current->nextptr; } if (prev == NULL) { newNode->nextptr = head; head = newNode; } else { newNode->nextptr = current; prev->nextptr = newNode; } return head; } // 删除指定值的节点 listnode_t* deletenode(listnode_t* head, int value) { listnode_t* current = head; listnode_t* prev = NULL; while (current!= NULL && current->pstdata->value!= value) { prev = current; current = current->nextptr; } if (current == NULL) { printf("Value not found in the list.\n"); return head; } if (prev == NULL) { head = current->nextptr; } else { prev->nextptr = current->nextptr; } free(current->pstdata); free(current); return head; } int main() { listnode_t* head = NULL; int choice; printf("please enter your choice: 1 is to insert an element to the list. 2 is to delete an element from the list. 3 is to quit.\n"); do { printf("? "); scanf("%d", &choice); switch (choice) { case 1: { int value; printf("enter an int to insert: "); scanf("%d", &value); head = insertnode(head, value); printlist(head); break; } case 2: { int value; printf("enter an int to be deleted: "); scanf("%d", &value); head = deletenode(head, value); printlist(head); break; } case 3: break; default: printf("Invalid choice. Please try again.\n"); } } while (choice!= 3); // 释放链表内存 listnode_t* temp; while (head!= NULL) { temp = head; head = head->nextptr; free(temp->pstdata); free(temp); } return 0; } ``` [2024-08-26 06:23:19 | AI写代码神器 | 828点数解答]

相关提问