写这道题目的意图呢是简单的总结下链表的使用,还有注意的事情
First 比较简单的写法,直接比较大小,不保存数据
int main() { int max = 0, sou; while (1) { printf("输入成绩\n"); scanf("%d", &sou); if (max < sou) { max = sou; } if (sou < 0) { break; } } printf("最大值是%d", max); return 0; }
第二种 链表的方式
我先讲一下遇到的问题
1.作为头结点指针的g_pHead,应该总是指向头结点,不要用作其他用途,如果需要使用头节点,应该创建普通的指针变量
2.不需要的东西不用传入链表,尤其是输入结束的标志位
3.释放链表和定义的动态数组
struct Node { int a; struct Node* pNEXT; }; struct Node* g_pHead = NULL; struct Node* g_pEnd = NULL; struct Node* Create_Node(int N) { struct Node* pTemp = (struct Node*)malloc(sizeof(struct Node)); pTemp->a = N; pTemp->pNEXT = NULL; return pTemp; } //尾添加 void AddNodeToList_End(int N) { struct Node* pTemp = Create_Node(N); if (g_pHead == NULL) { g_pHead = pTemp; g_pEnd = pTemp; } else { g_pEnd->pNEXT = pTemp; g_pEnd = pTemp; } } void List_Free_All(struct Node* TouPlace)// TouPlace应为g_pHead { struct Node* CANSHU = TouPlace; while (CANSHU != NULL) { struct Node* pt = CANSHU; //构建中间参数 CANSHU = CANSHU->pNEXT; //先指向下一个,再释放 free(pt); //释放内存 } g_pHead = NULL; g_pEnd = NULL; } int main() { int a; int max = 0; int n=0; int m = 0; int *G; int p = 0; while (1) { printf("请输入数据\n"); scanf("%d", &a); if (a < 0) { printf("数据输入完毕"); break; } AddNodeToList_End(a); } struct Node* Tplace = g_pHead; struct Node* Tplace2 = g_pHead; while (Tplace != NULL) { n++; Tplace = Tplace->pNEXT; } printf("人数为%d\n", n); G =(int*)malloc(n*sizeof(int)); while (Tplace2 != NULL) { G[p]= Tplace2->a; if (max < G[p]) { max = G[p]; } p++; Tplace2 = Tplace2->pNEXT; } //释放G的空间 free(G); //释放链表 List_Free_All(Tplace2); printf("最高的成绩是%d", max); return 0; }