//栈的链式存储表示(在栈中,top指向栈顶元素)
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct SqStack{
struct SqStack *next;
int data;
}Node;
struct SqStack *top;//栈顶指针
//初始化栈
void InitStack(){
top = NULL;
}
//判断栈是否为空
bool EmptyStack(){
if(top==NULL)
return true;
else
return false;
}
//返回栈中的元素个数
int StackLength(){
Node *s;
int num = 0;
s = top;
while(s){
num++;
s = s->next;
}
return num;
}
//获取栈顶元素
int GetTop(){
return top->data;
}
//入栈
void Push(int value){
Node *s = (Node *)malloc(sizeof(Node));
s->data = value;
s->next = top;
top = s;
}
//出栈
bool Pop(int *e){
if(!EmptyStack()){
Node *s;
s = top;
*e = top->data;
top = top->next;
free(s);
}else{
return false;
}
return true;
}
//遍历栈
void StackTraverse(){
Node* s = top;
while(s){
printf("%d ",s->data);
s = s->next;
}
printf("\n");
}
int main()
{
int i=1;
int e;
InitStack();//构造一个空栈
for(i=1;i<=13;i++){
Push(i);//进行入栈
}
printf("遍历栈元素如下:\n");
StackTraverse();//遍历栈
int len = StackLength();
printf("出栈操作元素如下:\n");
for(i=1;i<=len;i++){//不要把StackLength()放置此处,会出现逻辑错误。
if(Pop(&e))
{
printf("%d ",e);
}else{
printf("出栈失败\n");
}
}
printf("\n");
//再次进行入栈,不然会影响后续测试
for(i=1;i<=13;i++){
Push(i);
}
//获取栈顶元素
printf("栈顶元素:%d\n",GetTop());
return 0;
}