题解 | #KiKi学结构体和指针#
KiKi学结构体和指针
https://www.nowcoder.com/practice/0ab593ca56b1476eb05b1ff848fd7fcc
//难绷的数据结构,第一次犯了好多错。写到一半才发现可以有很多更好的选择,自己偏偏选了最难最烦的那一种。 //这就是改屎山的快感吗 #include<stdio.h> #include<assert.h> #include<stdlib.h> //基本元素声明 typedef struct Node { int data; struct Node* next; } Node; typedef struct Node* List; //typedef enum bool{ failure = 0,true = 1 } Bool; //接口声明 List Add(List list, int x);//增加一个节点,并返回该节点地址。 List Delete(List list, int x ,int* s);//删除指定节点,并返回首节点指针。 List findpre(List list,int x);//找到x的先驱元,若x为首元素则返回NULL,未找到也返回空 void pr_list(List list);//遍历链表 void free_List(List list); //具体实现 int main() { int n = 0; scanf("%d", &n); List list = NULL; int x = 0; for (int i = 0; i < n; i++) { scanf("%d", &x); list = Add(list, x); } //printf("%d",list ->next-> data); int m = 0; scanf("%d", &m); int y=0; list = Delete(list, m ,&y); //printf("%d",list->next->data); printf("%d\n",n-y); pr_list(list); // printf("\n%d",z); free_List(list); return 0; } //接口定义 List Add(List list, int x) { if (list == NULL) { list = malloc(sizeof(Node));//创建第一个节点 if (list == NULL) { printf("Out of space!"); return list; } else { list->data = x; list->next = NULL; } } else { list->next = Add(list->next, x); } return list; } List findpre(List list,int x) { List listtmp=NULL; /*if(list -> data == x) { //return NULL; ; }*/ //else //{ while(list -> next != NULL) { if(list -> next -> data == x) { listtmp = list ; break ; } else { list = list -> next; } //} } return listtmp; } List Delete(List list, int x,int* s) { int *y=s; List listbox = list; List listtmp = NULL; if((listtmp=findpre(list , x))!=NULL) { List listz = NULL; while(listtmp != NULL) { listz = listtmp -> next; listtmp -> next = listz -> next; free(listz); (*y)++; listtmp = findpre(listtmp , x); } } //else // { list = listbox; if (list->data == x) { (*y)++; listtmp = list; list = list->next; free(listtmp); } // } return list; } void pr_list(List list) { // int n=0; while (list != NULL) { printf("%d ", list->data); // n++; list = list->next; } //return n; } void free_List(List list) { List listtmp = NULL; while (list != NULL) { listtmp = list; list = list->next; free(listtmp); } }