创建c语言程序。程序实现如下功能1链表的插入输入要插入结点在链表中位置然后输入插入元素恢复为一个链表;2链表的删除输入要删除结点在链表中位置然后从链表中删除该结点。
#include <stdio.h> #include <stdlib.h>
// 定义链表结构体 struct Node { int data; struct Node* next; };
// 初始化链表 void initList(struct Node** head) { *head = NULL; }
// 插入结点 void insertNode(struct Node** head, int pos, int val) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = val; newNode->next = NULL; if (*head == NULL) { *head = newNode; return; } if (pos <= 0) { newNode->next = *head; head = newNode; return; } struct Node cur = *head; while (pos > 1 && cur->next != NULL) { cur = cur->next; pos--; } newNode->next = cur->next; cur->next = newNode; }
// 删除结点 void deleteNode(struct Node** head, int pos) { if (head == NULL) { return; } if (pos <= 0) { struct Node temp = *head; *head = (head)->next; free(temp); return; } struct Node cur = head; while (pos > 1 && cur->next != NULL) { cur = cur->next; pos--; } if (cur->next == NULL) { return; } struct Node temp = cur->next; cur->next = cur->next->next; free(temp); }
// 打印链表 void printList(struct Node* head) { struct Node* cur = head; while (cur != NULL) { printf("%d ", cur->data); cur = cur->next; } printf("\n"); }
int main() { struct Node* head; initList(&head); int n; printf("请输入操作数:\n"); scanf("%d", &n); while (n--) { int op, pos, val; printf("请输入操作类型:1-插入结点,2-删除结点\n"); scanf("%d", &op); if (op == 1) { printf("请输入插入位置和插入元素:\n"); scanf("%d%d", &pos, &val); insertNode(&head, pos, val); printf("插入后的链表:\n"); printList(head); } else if (op == 2) { printf("请输入删除位置:\n"); scanf("%d", &pos); deleteNode(&head, pos); printf("删除后的链表:\n"); printList(head); } } return 0;
原文地址: https://www.cveoy.top/t/topic/cdo7 著作权归作者所有。请勿转载和采集!