1、代码
#include <iostream>
#include <cstdlib>
#define MaxSize 10
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;
} LNode, * LinkStack;
int Length(LinkStack& S) {
int i = 0;
LNode* p = S;
while (p != NULL) {
p = p->next;
i++;
}
return i;
}
void InitLinkStack(LinkStack& S) {
S = NULL;
}
bool IsFullLinkStack(LinkStack& S) {
if (Length(S) == MaxSize)
return true;
return false;
}
bool IsEmptyLinkStack(LinkStack& S) {
if (S == NULL)
return true;
return false;
}
bool Push(LinkStack& S, ElemType x) {
if (IsFullLinkStack(S))
return false;
LNode* p = (LNode*)malloc(sizeof(LNode));
if (p == NULL)
return false;
p->data = x;
p->next = S;
S = p;
return true;
}
bool Pop(LinkStack& S, ElemType& x) {
if (IsEmptyLinkStack(S))
return false;
LNode* p = S;
x = p->data;
S = p->next;
free(p);
return true;
}
bool GetElem(LinkStack& S, ElemType& x) {
if (IsEmptyLinkStack(S))
return false;
x = S->data;
return true;
}
void Destroy(LinkStack& S) {
ElemType x;
while (!IsEmptyLinkStack(S))
Pop(S, x);
}
int main() {
LinkStack stack;
InitLinkStack(stack);
// Push elements into stack
ElemType a = 1;
ElemType b = 2;
ElemType c = 3;
ElemType d = 4;
ElemType e = 5;
ElemType j = 11;
ElemType f = 22;
ElemType g = 33;
ElemType h = 44;
ElemType i = 55;
Push(stack, a);
Push(stack, b);
Push(stack, c);
Push(stack, d);
Push(stack, e);
Push(stack, j);
Push(stack, f);
Push(stack, g);
Push(stack, h);
Push(stack, i);
int stackLength = Length(stack);
std::cout << "Stack Length: " << stackLength << std::endl;
// Check if the stack is empty
bool isEmpty = IsEmptyLinkStack(stack);
if (isEmpty) {
std::cout << "Stack is empty" << std::endl;
} else {
std::cout << "Stack is not empty" << std::endl;
}
// Check if the stack is full
bool isFull = IsFullLinkStack(stack);
if (isFull) {
std::cout << "Stack is full" << std::endl;
} else {
std::cout << "Stack is not full" << std::endl;
}
// Pop and print elements from stack
ElemType x;
while (Pop(stack, x)) {
std::cout << x << " ";
}
std::cout << std::endl;
Destroy(stack);
return 0;
}
2、运行结果