1.建立一个栈的结构体
typedef int elt;
typedef struct strack
{
elt data;
struct strack* next;
}Strack;
2.声明自定义函数
void InitStrack(Strack** q, Strack** top);
void PushStrack(Strack** q, Strack** top, elt s);
void PrintStrack(Strack* top);
3.初始化栈
void InitStrack(Strack** q, Strack** top)
{
if (*q == NULL)
{
(*q) = (Strack*)malloc(sizeof(Strack));
}
if (*q == NULL)
{
perror("*q");
return ;
}
if (*top == NULL)
{
(*q)->next = NULL;
}
(*q)->next = (*top);
*top = *q;
}
4.入栈
void PushStrack(Strack** q, Strack** top, elt s)
{
(*top)->data = s;
}
5.出栈
void PopStrack(Strack** top)
{
Strack* chag = *top;
*top = chag->next;
chag = NULL;
}
6.打印栈中元素
void PrintStrack(Strack* top)
{
while (top)
{
printf("%d", top->data);
top = top->next;
}
if (top == NULL)
{
printf("栈为空!");
}
}