数据结构基础:栈的实现
栈是程序中常见的数据结构,具有先进后出(LIFO)的特点。自己实现一个栈将会加深对于栈的理解。下面是一个简单的栈的实现。
头文件my_stack.h
#ifndef MY_STACK_H_INCLUDED
#define MY_STACK_H_INCLUDED
#define STACK_INIT_SZIE (100)
#define STACKINCREMENT (10)
typedef char SElemType;
typedef struct{
SElemType *mem;
int pos;
int size;
}SqStack;
SqStack * InitStack(int size);
int GetTop(SqStack *S,SElemType *e);
int Push(SqStack *S,SElemType *e);
int Pop(SqStack *S,SElemType *e);
int DestoryStack(SqStack **S);
void ClearStack(SqStack *S);
int StackLength(SqStack *S);
int StackEmpty(SqStack *S);
#endif // MY_STACK_H_INCLUDED
C文件my_stack.c
#include "my_stack.h"
#include <stdlib.h>
#include <string.h>
SqStack * InitStack(int size){
SqStack *S =(SqStack *)malloc(sizeof(SqStack));
if(!S) exit(-1);
S->mem=(SElemType *)calloc(size,sizeof(SElemType));
if(!(S->mem)) exit(-1);
S->size=size;
S->pos=0;
return S;
}
int GetTop(SqStack *S,SElemType *e){
if((!S)||(S->pos== 0)) return (-1);
*e=S->mem[S->pos-1];
return 0;
}
int Push(SqStack *S,SElemType *e){
if(S->pos>=S->size){
S->mem=(SElemType *)realloc(S->mem,sizeof(SElemType)* (S->size+=10));
if(!S->mem) exit(-1);
}
S->mem[S->pos++]=*e;
return 0;
}
int Pop(SqStack *S,SElemType *e){
if(S->pos != 0){
*e=S->mem[--S->pos];
return 0;
}
else return -1;
}
int DestoryStack(SqStack **S){
if((*S)){
free(*S);
}
else return -1;
if((*S)->mem){
free((*S)->mem);
}
else return -1;
*S=NULL;
return 0;
}
void ClearStack(SqStack *S){
S->pos=0;
}
int StackLength(SqStack *S){
int size=0;
if(S){
if(S->pos!=0){
size=S->pos-1;
}
}
return size;
}
int StackEmpty(SqStack *S){
int result = -1;
if(S){
result =(S->pos == 0);
}
return result;
}
C文件
测试程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "my_stack.h"
int main()
{
SqStack *stack=InitStack(5);
SElemType ele='A';
const char str[]="The GNU Assembler, part of the GNU tools, is used to convert assembly language source code";
for(int i=0;i<strlen(str);i++)
{
Push(stack,&str[i]);
}
puts(str);
printf("\r\n");
while(0 == Pop(stack,&ele)){
printf("%c",ele);
}
printf("\r\n");
printf("stack->size = %d",stack->size);
SqStack p=*stack;
DestoryStack(&stack);
//
printf("Hello world!\n");
return 0;
}
运行结果:
The GNU Assembler, part of the GNU tools, is used to convert assembly language s
ource code
edoc ecruos egaugnal ylbmessa trevnoc ot desu si ,sloot UNG eht fo trap ,relbmes
sA UNG ehT
stack->size = 95Hello world!
Process returned 0 (0x0) execution time : 0.019 s