本文主要针对栈的实现进行学习
首先是头文件,声明所要用的函数和结构体
#ifndef stack_H_
#define stack_H_
struct Stacks;
typedef struct Stacks *Stack;
//创建一个空栈
Stack create(int scale);
//判断是否为空栈
int Isempty(Stack S);
//Push
void Push(Stack S,int X);
//Pop
void Pop(Stack S);
#endif // stack_H_
然后定义结构体和相应的操作函数
#include <stdio.h>
#include <stdlib.h>
#define minstack 100
#include "main.h"
struct Stacks
{
int topofstack;
int capacity;
int *Array;
};
//创建一个空栈
Stack create(int scale)
{
if(scale<minstack)
{
printf("this stack is too small");
exit(1);
}
Stack S=malloc(sizeof(struct Stacks));
S->topofstack=-1;
S->capacity=scale;
S->Array=malloc(sizeof(int)*scale);
printf("success\n");
return S;
}
//判断是否是一个空的栈
int Isempty(Stack S)
{
return S->topofstack==-1;
}
//向栈中添加一个数字
void Push(Stack S,int X)
{
if(S->topofstack==S->capacity-1)
{
printf("error the stack is full\n");
exit(1);
}
S->Array[S->topofstack+1]=X;
S->topofstack++;
printf("Push success\n");
}
//Pop
void Pop(Stack S)
{
if(S->topofstack==-1)
{
printf("error,the stack is empty\n");
exit(1);
}
S->topofstack--;
printf("Pop success\n");
}
//取顶部元素
int top(Stack S)
{
if(S->topofstack==-1)
{
printf("error,the stack is empty\n");
exit(1);
}
return S->Array[S->topofstack];
}
//释放栈
void disposestack(Stack S)
{
free(S->Array);
free(S);
}
接下来构造一个栈来实现相应的操作
int main()
{
Stack s1=create(200);
printf("%d\n",Isempty(s1));
Push(s1,1);
Push(s1,2);
printf("%d\n",top(s1));
Pop(s1);
disposestack(s1);
return 0;
}
练习 1 构造一个栈,可以判断输入的字符串中的括号(圆括号,方括号,花括号)是否配对。
int main()
{
Stack s1=create(200);
char *string="asb[](..]..(kl)";
int tem_char;
int tem_top;
int i;
for(i=0;string[i]!='\0';i++)
{
tem_char=string[i];
if(tem_char==40||tem_char==91||tem_char==123)
Push(s1,tem_char);
if(tem_char==41||tem_char==93||tem_char==125)
{
tem_top=top(s1);
if(tem_top==-1)
{
printf("wrong\n");
break;
}
if(abs(tem_char-tem_top)>2)
break;
else
Pop(s1);
}
}
if(Isempty(s1))
printf("right\n");
else
printf("wrong\n");
return 0;
}