栈是按照“后进先出”的原则进行排序存储结构(类似于弹匣)。
栈分为静态栈和动态栈
静态栈可参考数组
动态栈通过指针进行连接,是离散存储的,本质上是链表。
栈主要用于存取(压栈、出栈)。
头文件
#ifndef _STACK_H_
#define _STACK_H_
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node
{
int data;
struct Node *pNext;
}NODE, *PNODE;
typedef struct stack
{
PNODE Ptop;
PNODE Pbottom
}STACK, *PSTACK;
PSTACK init();
void create(PSTACK stack,int val);
void create_arr(PSTACK,int);
void traversal(PSTACK stack);
void empty(PSTACK stack);
bool pop(PSTACK,int *);
void clear(PSTACK stack);
#endif
函数实现
#include"stack.h"
PSTACK init()
{
PSTACK amns=(PSTACK)malloc(sizeof(STACK));
if(NULL==amns)
{
printf("分配空间失败!");
exit(-1);
}
amns->Pbottom=(PNODE)malloc(sizeof(NODE));
if(NULL==amns->Pbottom)
{
printf("空间分配失败!");
exit(-1);
}
amns->Pbottom->pNext=NULL;
amns->Ptop=amns->Pbottom;
return amns;
}
void create(PSTACK stack,int val)
{
PNODE p=(PNODE)malloc(sizeof(NODE));
p->data=val;
p->pNext=stack->Ptop;
stack->Ptop=p;
return;
}
void create_arr(PSTACK stack,int cnt)
{
int val=0;
int i=0;
while(i<cnt)
{
printf("请输入要输入的数值:");
scanf("%d",&val);
PNODE p=(PNODE)malloc(sizeof(NODE));
p->data=val;
p->pNext=stack->Ptop;
stack->Ptop=p;
i++;
}
return;
}
bool empty1(PSTACK stack)
{
if(stack->Ptop==stack->Pbottom)
{
return true;
}
else
{
return false;
}
}
void traversal(PSTACK stack)
{
if(empty1(stack))
{
printf("栈为空,无法进行遍历操作!\n");
}
else
{
PNODE p=stack->Ptop;
while(NULL!=p->pNext)
{
printf("%d ",p->data);
p=p->pNext;
}
}
return;
}
bool pop(PSTACK stack,int *val)
{
if(empty1(stack))
{
return false;
}
else
{
*val=stack->Ptop->data;
PNODE p=stack->Ptop;
stack->Ptop=p->pNext;
free(p);
p=NULL;
return true;
}
}
void clear(PSTACK stack)
{
PNODE p=stack->Ptop;
while(NULL!=p->pNext)
{
stack->Ptop=p->pNext;
printf("清空的元素为%d\n",p->data);
free(p);
p=stack->Ptop;
}
free(stack);
return;
}
函数调用
#include"stack.h"
int main(int argc, const char *argv[])
{
PSTACK stack=NULL;
stack=init();
create(stack,1);
create(stack,2);
create(stack,3);
create_arr(stack,4);
traversal(stack);
printf("\n");
int val=0;
if(pop(stack,&val))
{
printf("出栈成功,删除的值为%d\n",val);
}
else
{
printf("栈为空,删除失败!");
}
traversal(stack);
printf("\n");
clear(stack);
return 0;
}