编写函数,长度最大为20个整型元素的线性表,插入、删除整数,没插入或删除一次后显示出变化后的线性表,在主函数中调用实现
1条回答 默认 最新
技术专家团-小桥流水 2021-11-13 21:40关注代码如下
#include <stdio.h> #include <stdlib.h> struct StNode { int data; struct StNode* next; }; struct StNode* CreateList() { int i,n; struct StNode* head,*p,*t; head = (struct StNode*)malloc(sizeof(StNode)); head->next = NULL; t = head; printf("请输入链表的长度:"); scanf("%d",&n); printf("请输入链表数据:"); for (i=0;i<n;i++) { p = (struct StNode*)malloc(sizeof(StNode)); scanf("%d",&(p->data)); p->next = NULL; t->next = p; t = p; } return head; } //插入 struct StNode* InsertList(struct StNode*head,int pos,int data) { struct StNode* p = head,*t; int i=1; while(i<pos && p) { p = p->next; i++; } if (p) { t = (struct StNode*)malloc(sizeof(StNode)); t->data = data; t->next = p->next; p->next = t; printf("插入成功\n"); }else printf("插入位置不合适,插入失败\n"); return head; } //删除 struct StNode* Delete(struct StNode* head,int pos) { int i = 1; struct StNode* p = head,*t; while(i<pos && p) { p = p->next; i++; } if (p) { t = p->next; p->next = t->next; free(t); t = 0; printf("删除成功\n"); }else printf("删除成功\n"); return head; } //显示 void show(struct StNode* head) { struct StNode* p = head->next; while(p) { printf("%d ",p->data); p = p->next; } printf("\n"); } //释放空间 void Free(struct StNode* head) { struct StNode* p; while(head) { p = head->next; free(head); head = p; } head = 0; } int main() { int pos,data; struct StNode* head = CreateList(); show(head); //插入 printf("请输入插入位置(从1开始)和数据:"); scanf("%d %d",&pos,&data); head = InsertList(head,pos,data); printf("插入后链表数据:"); show(head); //删除 printf("请输入删除位置(从1开始):"); scanf("%d",&pos); head = Delete(head,pos); printf("删除后链表数据:"); show(head); //释放空间 Free(head); return 0; }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报 编辑记录解决 2无用