69,382
社区成员
发帖
与我相关
我的任务
分享
S = CreatStack(S);
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//#define Stack_ElemType int
typedef int Stack_ElemType;// int
typedef struct StackNode {
struct StackNode* next;
Stack_ElemType data;
}StackNode,*LinkStack;
//链栈初始化 // 返回的是链栈的首地址
//StackNode* initStack(LinkStack S) {
StackNode* initStack(LinkStack *S)
{
*S = (LinkStack)malloc(sizeof(StackNode));
if (*S == NULL) {
printf("内存分配不成功!\n");
return 0;
}//;
(*S)->next = NULL;
return *S;
} //;
//创建链栈
StackNode* CreatStack(LinkStack S)
{
StackNode* p;
int j = 1;
Stack_ElemType t = 0;
while (j) {
printf("请输入栈顶元素,输入-1时结束创建\n ");
//scanf_s("%d", &t);
scanf("%d", &t);
if (t == -1) {
break;
}
p = (LinkStack)malloc(sizeof(StackNode));
if (p == NULL) { // 动态分配空间后要进行判断否则会有警告
printf("内存分配不成功!\n");
//return 0;
return S;
}//;
p->data = t;
p->next = S;
S = p;
}//;
return S;
}
// 链栈的压栈
void pushStack(LinkStack &S, Stack_ElemType e) {
StackNode* p;
p = (LinkStack)malloc(sizeof(StackNode));
if (p == NULL) { // 动态分配空间后要进行判断否则会有警告
printf("内存分配不成功!\n");
return;
}
p->data = e;
p->next = S;
printf("%d\n", p->data);
S = p;// 现在栈顶为刚压栈的p的结点
};
StackNode* popStack(LinkStack S, Stack_ElemType* e) {
StackNode *p;
if (S == NULL) {
//return 0;
return NULL;
}
*e = S->data;
p = S;
S = S->next;
free(p);
return S;
}//;
Stack_ElemType StackLenth(StackNode S) {
int i = 1;
StackNode* p;
p = S.next;
while (p) {
p = p->next;
i++;
}//;
return i;
}
int main(void) {
StackNode* S;
S = NULL;
Stack_ElemType j = 0;
S = initStack(&S);
S = CreatStack(S);
//for (int i = 0; i < 5; i++) {
for (int i = 0; S; i++) {
S = popStack(S, &j);
if (S)
printf("%d\n", j);
}//;
S = popStack(S, &j);
if (S)
printf("%d\n", j);
return 0;
}