头文件
#ifndef _STACK_H_
#define _STACK_H_
#include <stdio.h>
#include "stdlib.h"
#define N 1024
typedef int st_data_t;
typedef struct sqstack{
st_data_t grades[N];
int top;
}st_node,*st_pnode;
//创建
st_pnode create_stacklist();
//判满
int full_stacklist(st_pnode X);
//判空
int empty_stacklist(st_pnode X);
//插入
int insert_stacklist(st_pnode X,st_data_t data);
//打印
int show_stacklist(st_pnode X);
//查 根据元素查位置
int serch_stacklist(st_pnode X,st_data_t data);
//查 根据位置查元素
int serch2_stacklist(st_pnode X,int pos);
//删除 删除顶部
int delete_stacklist(st_pnode X);
//清空
int clear_stacklist(st_pnode X);
//摧毁
int destory_stacklist(st_pnode *X);
功能代码
#include "stack.h"
//创建
st_pnode create_stacklist()
{
st_pnode X=(st_pnode)malloc(sizeof(st_node));
if(NULL == X)
{
printf("create is error\n");
return 0;
}
X->top=0;
return X;
}
//判满
int full_stacklist(st_pnode X)
{
if(NULL == X)
{
printf("create is error\n");
return 0;
}
if(N == X->top)
return 1;
else
return -1;
}
//判空
int empty_stacklist(st_pnode X)
{
if(NULL == X)
{
printf("create is error\n");
return 0;
}
if(0 == X->top)
return 1;
else
return -1;
}
//插入
int insert_stacklist(st_pnode X,st_data_t data)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == full_stacklist(X))
{
printf("X is full\n");
return -1;
}
X->grades[X->top]=data;
X->top++;
return 0;
}
//打印
int show_stacklist(st_pnode X)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == empty_stacklist(X))
{
printf("X is empty\n");
return -1;
}
int i,j=0;
for(i=X->top-1;i>=0;i--)
{
printf("gardes[%d]=%d\n",j,X->grades[i]);
j++;
}
return 0;
}
//查 根据元素查位置
int serch_stacklist(st_pnode X,st_data_t data)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == empty_stacklist(X))
{
printf("X is empty\n");
return -1;
}
int i=0,j=X->top-1;
while(j)
{
if(data == X->grades[j])
{
return i;
}
j--;
i++;
}
printf("无此元素\n");
return -1;
}
//查 根据位置查元素
int serch2_stacklist(st_pnode X,int pos)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == empty_stacklist(X))
{
printf("X is empty\n");
return -1;
}
if(pos<0 || pos>X->top)
{
printf("pos is error\n");
return 1;
}
int i=X->top;
return X->grades[i-pos];
}
//删除 删除顶部
int delete_stacklist(st_pnode X)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == empty_stacklist(X))
{
printf("X is empty\n");
return -1;
}
printf("%d被删除\n",X->grades[X->top-1]);
X->top--;
return 0;
}
//清空
int clear_stacklist(st_pnode X)
{
if(NULL == X)
{
printf("X is NULL\n");
return 0;
}
if(1 == empty_stacklist(X))
{
printf("X is empty\n");
return -1;
}
X->top=0;
return 1;
}
//摧毁
int destory_stacklist(st_pnode *X)
{
if(NULL == *X)
{
printf("X is NULL\n");
return 0;
}
free(*X);
*X=NULL;
return 0;
}