建立一个结点值为学生姓名和成绩的长度大于5的链表,在任意位置进行插入、删除结点操作
1条回答 默认 最新
- 技术专家团-小桥流水 2021-11-18 16:34关注
代码如下:
#include <stdio.h> #include <stdlib.h> struct Student { char name[20]; int score; }; struct Node { struct Student stu; struct Node* next; }; //创建链表 struct Node* createList() { int i,n; struct Node* head,*p,*t; head = (struct Node*)malloc(sizeof(struct Node)); head->next = NULL; p = head; printf("请输入学生个数:"); scanf("%d",&n); for (i=0;i<n;i++) { printf("请输入学生%d的姓名和成绩" , i+1); t = (struct Node*)malloc(sizeof(struct Node)); scanf("%s %d",t->stu.name , &(t->stu.score)); t->next = NULL; p->next = t; p = t; } return head; } //显示链表 void printList(struct Node* head) { struct Node* p; if(head == NULL) return; p = head->next; while(p) { printf("%s : %d\n",p->stu.name,p->stu.score); p = p->next; } } //获取链表长度(不含头结点) int getListLength(struct Node* head) { int len = 0; struct Node* p; if(head == NULL) return len; p = head->next; while(p) { len++; p = p->next; } return len; } //插入链表 struct Node* insertList(struct Node* head,int pos, struct Student stu) { int len; struct Node* p,*t; len = getListLength(head); if (pos < 1 || pos > len+1) { printf("插入位置不合适,插入失败\n"); return head; } t = (struct Node*)malloc(sizeof(struct Node)); t->stu = stu; t->next = NULL; p = head; pos--; while(pos-- && p ) { p = p->next; } if (p) { t->next = p->next; p->next = t; } return head; } //删除链表节点 struct Node* deleteList(struct Node* head,int pos) { int len; struct Node* p,*t; len = getListLength(head); if (pos < 1 || pos > len) { printf("删除位置不合适,删除失败\n"); //cout << "删除位置不合适,删除失败" <<endl; return head; } // p = head; pos--; while(pos-- && p ) { p = p->next; } if (p) { if(p->next) { t = p->next; p->next = t->next; free(t); t = 0; } } return head; } int main() { int pos; struct Student stu; struct Node* head = createList(); printf("链表数据为:\n"); printList(head); printf("请输入插入位置:"); scanf("%d",&pos); printf("请输入插入的学生姓名和成绩:" ); scanf("%s %d",stu.name,&stu.score); head = insertList(head,pos,stu); printf("插入后链表数据为:\n"); printList(head); printf("请输入需要删除的位置:"); scanf("%d",&pos); head = deleteList(head,pos); printf("删除节点后链表的数据:\n"); printList(head); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
- ¥20 怎么用dlib库的算法识别小麦病虫害
- ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
- ¥15 java写代码遇到问题,求帮助
- ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
- ¥15 有了解d3和topogram.js库的吗?有偿请教
- ¥100 任意维数的K均值聚类
- ¥15 stamps做sbas-insar,时序沉降图怎么画
- ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
- ¥15 关于#Java#的问题,如何解决?