1、类型定义
#define MAX_SIZE 50
typedef struct node{
int element;
struct node* next;
}S_NODE;
typedef struct
{
S_NODE* top;
int maxNum;
int nowNum;
}S_STACK;
2、创建空堆栈
void CreateStack(S_STACK* stack, int maxsize)
{
stack->top = NULL;
stack->maxNum = maxsize;
stack->nowNum = 0;
}
3、堆栈是否为空
int IsEmpty(S_STACK s)
{
return s.nowNum == 0;
}
4、堆栈是否为满
int IsFull(S_STACK s)
{
return s.nowNum == s.maxNum;
}
5、Push一个元素
void Push(S_STACK* s, int ele)
{
S_NODE* tmp = NULL;
if(IsFull(*s))
return;
tmp = (S_NODE*)malloc(sizeof(S_NODE));
if(tmp == NULL)
return;
tmp->next = NULL;
tmp->element = ele;
if(s->top == NULL)
s->top = tmp;
else
{
tmp->next = s->top;
s->top = tmp;
}
(s->nowNum)++;
}
6、Pop一个元素
void Pop(S_STACK* s, int* ele)
{
S_NODE* tmp = NULL;
if(IsEmpty(*s))
return;
tmp = s->top;
*ele = tmp->element;
s->top = tmp->next;
free(tmp);
(s->nowNum)--;
}
7、获取栈顶元素
void StackTop(S_STACK* s, int* ele)
{
S_NODE* tmp = NULL;
if(IsEmpty(*s))
return;
tmp = s->top;
*ele = tmp->element;
}
8、打印堆栈
void PrintStack(S_STACK* s)
{
S_NODE* tmp = NULL;
tmp = s->top;
printf("Stack Contains: ");
while(tmp)
{
printf("%d ", tmp->element);
tmp = tmp->next;
}
}
9、测试main
int main()
{
int i;
S_STACK stack;
CreateStack(&stack, 10);
for(i = 0; i < 20; i++)
{
Push(&stack, i);
}
PrintStack(&stack);
printf("end...");
return 0;
}
10、输出
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d68fe1654b350df2a36bb8f0b512ff65.jpeg)