可以设置将栈的结构体设置俩个别名,一个Stack,另一个*Lstack,也可以新创建一个栈的结构体,放它的头指针和长度,也可以设置头结点或者不设置,但这里设置用途不大,读者可据喜好自行设计。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef int ElemType;
typedef struct Stack
{
ElemType data;
struct Stack* next;
}Stack;
typedef struct
{
struct Stack* top;
int cursize;
}Lstack;
void Init_stack(Lstack *pstack)
{
assert(pstack != nullptr);
pstack->top = nullptr;
pstack->cursize = 0;
}
Stack* BuyNode()
{
Stack* s = (Stack*)malloc(sizeof(Stack));
if (nullptr == s) exit(1);
memset(s, 0, sizeof(Stack));
return s;
}
bool Push(Lstack* pstack, ElemType& val)
{
assert(pstack != nullptr);
Stack* newnode = BuyNode();
newnode->data = val;
newnode->next = pstack->top;
pstack->top = newnode;
pstack->cursize += 1;
return true;
}
bool IsEmpty(Lstack* pstack)
{
assert(pstack != nullptr);
return pstack->top == nullptr;
}
bool Pop(Lstack* pstack, ElemType& e)
{
assert(pstack != nullptr);
if (IsEmpty(pstack)) exit(1);
Stack* p = pstack->top;
pstack->top = p->next;
e = p->data;
free(p);
p = nullptr;
pstack->cursize -= 1;
return true;
}
bool GetTop(Lstack* pstack, ElemType& e)
{
assert(pstack != nullptr);
if (IsEmpty(pstack)) exit(1);
e = pstack->top->data;
return true;
}
int Get_Lenght(Lstack* pstack)
{
assert(pstack != nullptr);
return pstack->cursize;
}
void Print_stack(Lstack* pstack)
{
assert(pstack != nullptr);
Stack* p = pstack->top;
while (p!= nullptr)
{
printf("%3d", p->data);
p = p->next;
}
printf("\n");
}
void Destroy_stack(Lstack* pstack)
{
assert(pstack != nullptr);
int n = 0;
while (pstack->top != nullptr)
{
Pop(pstack, n);
}
}