#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct linkNode {
char data;
struct linkNode* next;
}linkStNode;
//初始化栈
void InitStack(linkStNode*& s) {
s = (linkStNode*)malloc(sizeof(linkStNode));
s->next = NULL;
}
//判断栈是否为空
bool EmptyStack(linkStNode* s) {
return (s->next == NULL);
}
//进栈
bool PushStack(linkStNode*& s, char c) {
linkStNode* n = (linkStNode*)malloc(sizeof(linkStNode));
n->data = c;
n->next = s->next;
s->next = n;
return true;
}
//出栈
bool PopStack(linkStNode*& s, char& c) {
linkStNode* p = NULL;
if (s->next == NULL)
{
return false;
}
else {
p = s->next;
c = p->data;
s->next = p->next;
free(p);
return true;
}
}
//销毁栈
void DestroyStack(linkStNode*& s) {
linkStNode* pre = s, * p = s->next;
while (p != NULL)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main() {
linkStNode* S = NULL;
char n = '\0';
InitStack(S);
cout << (EmptyStack(S) ? "空" : "非空") << endl;
cout << "将a,b,c,d,e按顺序依次进栈" << endl;
PushStack(S, 'a');
PushStack(S, 'b');
PushStack(S, 'c');
PushStack(S, 'd');
PushStack(S, 'e');
cout << (EmptyStack(S) ? "空" : "非空") << endl;
while (!EmptyStack(S)) {
PopStack(S, n);
cout << n << endl;
}
cout << (EmptyStack(S) ? "空" : "非空") << endl;
DestroyStack(S);
return 0;
}
c链栈
于 2023-05-19 20:23:19 首次发布