解题思路:
注意事项:
参考代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> //结构体定义 typedef struct node{ int data; struct node *next; }node,*List; //判断是否申请成功 void isOk(List L){ if (L == NULL){ printf("申请失败"); exit(0); } } //创建函数(尾插法),输出结果逆序 List LinkedListCreatT(int n,int *len){ //初始化头结点 node *L; L = (node *)malloc(sizeof(node)); L->next = NULL; isOk(L); *len = n; int x; for (int i=0;i<n;i++){ scanf("%d",&x); node *p; p = (node *)malloc(sizeof(node)); isOk(p); p->data = x; p->next = L->next; L->next = p; // printf("%p ",p); } // printf("%p ",L); return L; } //删除 List LinkedDelete(List L,int x,int *len){ if (x < 0 || x > *len){ printf("delete fail\n"); }else{ if (L->next == NULL){ printf("Link list is empty\n"); }else{ node *p,*pre; if (x==1){ p = L->next; L->next = p->next; free(p); printf("delete OK\n"); (*len)--; return L; }else{ p = L->next; for (int temp = 1;temp<x;temp++){ pre = p; p = p->next; } pre->next = p->next; free(p); printf("delete OK\n"); (*len)--; return L; } } } return L; } //插入 void LinkedListInsert(List L,int x,int k,int *len){ if (x < 0 || x > *len+1){ printf("insert fail\n"); }else{ node *pre; pre = L; for (int temp=1;temp<x;temp++){ pre = pre->next; } node *p; p = (node *)malloc(sizeof(node)); isOk(p); p->data = k; p->next = pre->next; pre->next = p; (*len)++; printf("insert OK\n"); } } //获取第a个元素 void LinkedListGet(List L,int x){ if (L->next == NULL){ printf("Link list is empty\n"); }else{ node *p; p = L; for (int temp=1;temp<=x;temp++){ p = p->next; } printf("%d\n",p->data); } } //显示链表 void show(List L){ if (L->next == NULL){ printf("Link list is empty\n"); }else{ node *p; p = L->next; while(p){ printf("%d ",p->data); p = p->next; } printf("\n"); } } //主函数 int main(){ List list; int len; int n; scanf("%d",&n); list = LinkedListCreatT(n,&len); int m; scanf("%d",&m); for (int i=0;i<m;i++){ char order[7]; scanf("%s",&order); if (strcmp(order,"show") == 0){ show(list); } else if (strcmp(order,"delete") == 0){ int k; scanf("%d",&k); list = LinkedDelete(list,k,&len); } else if (strcmp(order,"insert") == 0){ int y,u; scanf("%d%d",&y,&u); LinkedListInsert(list,y,u,&len); } else if (!strcmp(order,"get")){ int r; scanf("%d",&r); LinkedListGet(list,r); } } return 0; }
0.0分
1 人评分
c primer plus 第十二章 12.1小节浏览:400 |
C语言程序设计教程(第三版)课后习题6.7 (C语言代码)浏览:548 |
C语言考试练习题_一元二次方程 (C语言代码)浏览:606 |
幸运数 (C++代码)浏览:1309 |
小九九 (C语言描述,不看要求真坑爹)浏览:1006 |
敲七 (C++代码)浏览:1119 |
母牛的故事 (C语言代码)浏览:625 |
班级人数 (C语言代码)浏览:980 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:514 |
C语言程序设计教程(第三版)课后习题5.5 (Java代码)浏览:563 |