#include<stdio.h>
#include <stdlib.h>
#define ElementType int
//堆栈的链式存储的单个节点
struct SNode {
ElementType Data;
struct SNode* Next;
};
typedef struct SNode* Stack;
//创建空的堆栈
Stack CreateStack()
{
Stack s = (Stack)malloc(sizeof(struct SNode));
s->Next = nullptr;
return s;
}
//非空为0,空为1
bool IsEmpty(Stack s)
{
return s->Next == nullptr ? true : false;
}
//虚拟头节点.
void Push(ElementType item, Stack s)
{
//将元素压入堆栈
Stack node = (Stack)malloc(sizeof(struct SNode));
node->Data = item;
node->Next = s->Next;
s->Next = node;
}
ElementType Pop(Stack s)
{
//删除并返回栈顶元素
if (IsEmpty(s)) {
printf("stack is empty\n");
return NULL;
}
Stack node = s->Next;
ElementType value = node->Data;
s->Next = node->Next;
free(node);
return value;
}
//测试程序
int main()
{
Stack s = CreateStack();
bool status;
status = IsEmpty(s);
if (status) {
printf("栈为空\n");
}
else {
printf("栈非空\n");
}
//插入一个元素10;
Push(10, s);
Push(20, s);
ElementType value = Pop(s);
printf("栈顶元素=%d\n", value);
value = Pop(s);
printf("栈顶元素=%d\n", value);
}
11-10
296
07-15
327
10-18
1633