栈和队列是和线性表不相同的两类重要的抽象数据类型
栈
1.顺序栈
#define MAXSIZE 100
typedef int datatype
typedef struct
{
datatype data[MAXSIZE];
int top;
//默认0就是栈低
}seqstack;
栈的基本操作
进栈
void PUSH(seqstack *s,datatype x)
{
if(s->top==MAXSIZE)
{
printf("OverFlow!\n");
return 0;
}
s->data[s->top]=x;
s->top++;
return 1;
}
输出
void OUT(seqstack *s)
{
for(int i=0;i<s->top;i++)
{
printf("%d",s->data[i]);
}
printf("\n");
}
void main()
{
//用于通过用户输入初始化一个栈
struct seqstack *SS;
datatype x;
SS = (seqstack*)malloc(sizeof(seqstack));
SS->top=0;
printf("please inputs the datas (end with code 0):");
scanf("%d",&x);
while(x!=0)
{
PUSH(SS,x);
scanf("%d",&x);
}
OUT(SS);
}
退栈
datatype POP(seqstack *s)
{
datatype x;
if(s->top==0)
{
printf("The stack is empty!");
return 0;
}
s->top--;
x=s->data[s->top];
return x;
}
printf("Do you delete the data?\n");
scanf("%c",&ch);
if(ch=='y' || ch=='Y')
{
x = POP(SS);
if(x)
{
printf("The element %d is deleted!\n",x);
OUT(SS);
}
}
应用
十进制转换为二进制
void 10_2(int x)
{
seqstack *SS;
SS=(seqstack*)malloc(sizeof(seqstack));
while(x)
{
y=x%2;
PUSH(SS,y);
x/=2;
}
while(SS->top>0)
{
y=POP(SS);
printf("%d",y);
}
}
括号匹配检测
左括号就进栈,右括号就弹出一个与之比较
int test(char *str)
{
seqstack *SS;
char *p;
datatype x;
SS = (seqstack*)malloc(sizeof(seqstack));
SS->top=0;
for(p=str;*p!='\0';p++)
{
if(*p=='('||*p=='['||*p=='{')
PUSH(SS,*p);
else if(*p==')'||*p==']'||*p=='}')
{
x=POP(SS);
if(*p==')'&&x!='(') return 0;
if(*p==']'&&x!='[') return 0;
if(*p=='}'&&x!='{') return 0;
}
}
if(SS->top!=0) return 0;
return 1;
}
void main()
{
char str[80];
int flag;
printf("Please input the string:\n");
gets(str);
flag=test(str);
if(flag) prinf("Yes!\n");
else printf("NO!\n");
getch();//暂停程序
}
2.链栈
链栈的存储结构
typedef struct StackNode()
{
ElemType data;
struct StackNode *next;
}*LinkStack;
初始化栈
void InitStack(LinkStack *s)
{
S=NULL;
return ok;
}
入栈
status Push(LinkStack &S,ElemType x)
{
StackNode p=New StackNode;
p->data=x;
p->next=s;
s=p;
return ok;
}
出栈
status POP(LinkStack &S,ElemType &x)
{
if(S==NULL)
return error;
x = S->data;
p=s;
s=s->next;
delete p;
return ok;
}
取栈顶元素
ElemType GetTop(LinkStack S)
{
if(S!=NULL)
{
return S->data;
}
}