#include <stdio.h>
#include <malloc.h>
typedef struct SNode
{
int data;
struct SNode *next;
} * PNode, Node;
typedef struct SStack
{
PNode pBottom;
PNode pTop;
} * PStack, Stack;
//初始化栈
void init(PStack);
// 压栈
void push(PStack, int);
// 出栈
bool pop(PStack, int *);
// 输出栈
void show(PStack);
// 判断栈是不是为空
bool is_empty(PStack);
// 清空栈
void clear(PStack);
int main()
{
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
show(&s);
int val;
// clear(&s);
if (pop(&s, &val))
{
printf("出栈成功!出栈的元素是%d\n", val);
}
else
{
printf("出栈失败!");
}
show(&s);
push(&s, 5);
printf("压栈成功!\n");
show(&s);
return 0;
}
void init(PStack pStack)
{
pStack->pBottom = (PNode)malloc(sizeof(Node));
if (NULL == pStack->pBottom)
{
printf("初始化失败!");
}
// 此时栈顶和栈底指向相同
pStack->pTop = pStack->pBottom;
pStack->pTop->next = NULL;
}
bool is_empty(PStack pStack)
{
if (pStack->pTop != pStack->pBottom)
{
return false;
}
else
{
return true;
}
}
void push(PStack pStack, int val)
{
// 创建一个新的节点
PNode newP = (PNode)malloc(sizeof(Node));
newP->data = val;
//根据栈顶位置添加元素
newP->next = pStack->pTop;
//更新栈顶位置
pStack->pTop = newP;
}
bool pop(PStack pStack, int *val)
{
if (is_empty(pStack))
{
return false;
}
else
{
PNode pNode = pStack->pTop;
*val = pNode->data;
pStack->pTop = pNode->next;
free(pNode);
pNode = NULL;
return true;
}
}
void show(PStack pStack)
{
// 栈顶指向不动
PNode pNode = pStack->pTop;
while (pNode != pStack->pBottom)
{
printf("%d\t", pNode->data);
pNode = pNode->next;
}
printf("\n");
}
void clear(PStack pStack)
{
if (is_empty(pStack))
{
return;
}
PNode p, q;
p = pStack->pTop;
while (p != pStack->pBottom)
{
//这里是易出错的地方
q = p->next;
free(p);
p = q;
}
pStack->pTop = pStack->pBottom;
}
C++实现链式栈
最新推荐文章于 2024-11-09 13:08:09 发布