【发布时间】:2018-05-13 14:50:48
【问题描述】:
几天前我们在课堂上写了这段代码,老师试图解释它,我们大多数人都不明白。我现在几乎完全理解它了,但是为什么第二个 while in main 不起作用?它应该在弹出之前输出一个名称。
#include <stdio.h>
#include<stdlib.h>
typedef struct STK_S{
char name[100];
struct STK_S *next;
}STK;
int push(STK **ppS, STK *pD);
int pop(STK **ppS, STK *pD);
int main(){
STK *pS, d;
pS = NULL;
while (1){
printf_s("Ime ");
gets_s(d.name, 100);
if (d.name[0] == 0)
break;
push(&pS, &d);
}
while (pop(&pS, &d))
printf_s("\n%s", d.name);
return 0;
}
int push(STK **ppS, STK *pD){
STK *pt;
pt = (STK *)malloc(sizeof(STK));
if (pt == NULL)
return 0;
*pt = *pD;
pt->next = *ppS;
*ppS = pt;
return 1;
}
int pop(STK **ppS, STK *pD){
STK *pt;
if (*ppS == NULL){
printf("Empty stack.\n");
return NULL;
}
*pD = **ppS;
pt = *ppS;
*ppS = pt->next;
free(pt);
return 0;
}
【问题讨论】:
-
在 pop() 结束时返回 1。
-
是的,我复制了正确的代码,我知道这些返回值相同(有点)。多谢你们。现在可以使用了。
-
NULL是 null-pointer 文字。您不想从返回int的函数中返回。 -
顺便说一句,不需要像 C 而不是 C++ 那样从
malloc()转换结果。
标签: c list while-loop stack