#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define Stack_ElemType int
typedef struct StackNode {
struct StackNode* next;
Stack_ElemType data;
}StackNode,*LinkStack;
//鏈堆疊初始化 // 回傳的是鏈堆疊的首地址
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);
if (t == -1) {
break;
}
p = (LinkStack)malloc(sizeof(StackNode));
if (p == NULL) { // 動態分配空間后要進行判斷否則會有警告
printf("記憶體分配不成功!\n");
return 0;
};
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;
}
*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++) {
S = popStack(S, &j);
printf("%d\n", j);
};
S = popStack(S, &j);
printf("%d\n", j);
return 0;
}
請問一下 我加紅的字體 為什么在這個函式內更改了S 的 地址 回傳函式的時候卻是已經被釋放的p的地址呢?
但是我又回傳了S的地址才可以繼續下去
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/259874.html
標籤:C語言
下一篇:求一元二次方程的根
