#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
typedef int ElemType;
#define STACK_INIT_SIZE 20
typedef struct Stack
{
ElemType *base;
int top;
int capacity;
}Stack;
bool IsFull(Stack *st)
{
return st->top >= st->capacity;
}
bool IsEmpty(Stack *st)
{
return st->top == 0;
}
void InitStack(Stack *st)
{
st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
assert(st->base != NULL);
st->capacity = STACK_INIT_SIZE;
st->top = 0;
}
bool Push(Stack *st, ElemType x)
{
if(IsFull(st))
{
cout<<"栈已满,"<<x<<"不能入栈!"<<endl;
return false;
}
st->base[st->top++] = x;
return true;
}
bool Pop(Stack *st)
{
if(IsEmpty(st))
{
cout<<"栈以空,不能出栈!"<<endl;
return false;
}
st->top--;
return true;
}
bool Pop(Stack *st,ElemType *v)
{
if(IsEmpty(st))
{
cout<<"栈以空,不能出栈!"<<endl;
return false;
}
*v = st->base[--st->top];
return true;
}
ElemType GetTop(Stack *st)
{
if(IsEmpty(st))
{
cout<<"栈以空,不能出栈!"<<endl;
return -1;
}
else
{
return st->base[st->top-1];
}
}
void clear(Stack *st)
{
st->top = 0;
}
void destroy(Stack *st)
{
free(st->base);
st->base = NULL;
st->top = 0;
st->capacity = 0;
}
void ShowStack(Stack *st)
{
for(int i=st->top-1; i>=0; --i)
{
cout<<st->base[i];
}
cout<<endl;
}
函数实现部分
#include"Stack.h"
///
Stack st;
void convert_8(int a)//非负十进制转换成八进制
{
while(a)
{
Push(&st,a%8);
a=a/8;
}
ShowStack(&st);
}
char* convert_16(int value)//非负十进制转换成十六进制
{
static char Buffer[sizeof(int)*2+1];
int mod;
for(int i=sizeof(int)*2-1; i>=0; --i)
{
mod = value % 16;
if(mod < 10)
{
Buffer[i] = mod + '0';
}
else
{
Buffer[i] = (mod-10) + 'A';
}
value /= 16;
}
//Buffer[i] = "0123456789ABCDEF"[value%16];用两行代替for循环中的内容
// value /= 16;
return Buffer;
}
void main()
{
InitStack(&st);
unsigned long value = 480;
Convert_2(value);
ShowStack(&st);
cout<<Convert_16(value)<<endl;
}
//
/
bool cheak(char *s)//括号匹配的检验
{
Stack st;
InitStack(&st);
while(*s != '\0')
{
if(*s=='[' || *s=='(')
Push(&st,*s);
else if(*s == ']')
{
if(GetTop(&st) != '[')
return false;
Pop(&st);
}
else if(*s == ')')
{
if(GetTop(&st) != '(')
return false;
Pop(&st);
}
s++;
}
return IsEmpty(&st);
}
void main()
{
char *str = "[([()][()])]";
bool flag = cheak(str);
if(flag)
cout<<"OK"<<endl;
else
cout<<"Error"<<endl;
}
///
*/
void LineEdit()//行编辑的检验
{
Stack st;
InitStack(&st);
char ch=getchar();
while(ch!=EOF)
{
while(ch!='\n'&&ch!=EOF)
{
switch(ch){
case'#':
Pop(&st);
break;
case'@':
clear(&st);
break;
default:
Push(&st,ch);
break;
}
}
ch=getchar();
}
ShowStack(&st);
}
void main()
{
LineEdit();
}