1.链栈的结构定义及其初始化
#include<stdio.h>
#include<stdlib.h>
typedef struct Linknode {
int data;
struct Linknode *next;
}LiStackNode,*LiStack;
bool InitStack(LiStack &S) {
S = (LiStackNode *)malloc(sizeof(LiStackNode));
if (S==NULL)
{
return false;
}
S->next = NULL;
return true;
}
2.入栈
bool Push(LiStack &top,int x) {
LiStackNode *temp;
temp = (LiStackNode *)malloc(sizeof(LiStackNode));
if (temp==NULL)
{
return false;
}
temp->data = x;
temp->next = top->next;
top->next = temp;
return true;
}
3.出栈
bool Pop(LiStack &top, int &x) {
LiStackNode *temp;
temp = top->next;
if (temp==NULL)
{
return false;
}
top->next = temp->next;
x = temp->data;
free(temp);
return true;
}
4.测试
int main() {
LiStack S;
InitStack(S);
if (Push(S, 1))
{
printf("1入栈\n");
}
if (Push(S, 2))
{
printf("2入栈\n");
}
int x;
if (Pop(S, x))
{
printf("%d出栈\n",x);
}
if (Pop(S, x))
{
printf("%d出栈\n", x);
}
return 0;
}