第一个作业是:数值转换
-------------------------------------------------------------------
/*堆栈的一个应用,来进行数值的转换*/
#include "stdio.h"
#define MAXSIZE 50
struct Stack{
int top;
int sLink[MAXSIZE];
};
struct Stack *initStack()
{struct Stack *tem;
if((tem=(struct Stack*)malloc(sizeof(struct Stack)))==NULL)
{printf("系统无法分配空间.");
exit(1);
}
else
{tem->top=0;
tem->sLink[tem->top]=-1;
}
return tem;
}
void push(struct Stack *stack,int item)
{if(stack->top==MAXSIZE-1)
{printf("栈满");
exit(1);
}
else
{stack->top++;
stack->sLink[stack->top]=item;
}
}
int pop(struct Stack *stack)
{int tem;
if(stack->top==0)
{printf("栈为空");
exit(1);
}
else{
tem=stack->sLink[stack->top];
stack->top--;
}
return tem;
}
void coversion(int k,struct Stack *stack)
{printf("开始转换\n转换为八进制的结果为:");
while(k)
{push(stack,k%8);
k=k/8;
}
while(stack->top)
printf("%d",pop(stack));
printf("\n数值转换结束\n");
}
void main()/*主程序运行,来将66转换成为八进制*/
{struct Stack *stack;
int k=0;
printf("请输入需要转换的数字:");
scanf("%d",&k);
stack=initStack();
coversion(k,stack);
printf("Done.");
}
运行情况:
E:\work\workspace1016\myc\Release>myc
请输入需要转换的数字:99
开始转换
转换为八进制的结果为:143
数值转换结束
Done.
-------------------------------------------------------------------
第二个是匹配:
-------------------------------------------------------------------
//在g++上调试通过
#include "stdio.h"
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
//定义顺序堆栈
#define STACK_SIZE 100 //存储空间初始分配量
#define STACK_INC 10 //存储空间分配增量
typedef char Elem;
typedef struct{
Elem *base; //栈底指针
Elem *top; //栈顶指针
int size; //当前已分配的存储空间
}SqStack;
typedef int Status;
//创建空堆栈,栈顶指针和栈底指针相等时,栈为空
Status CreatStack(SqStack &S)
{
S.base=(Elem *)malloc(STACK_SIZE*sizeof(Elem));
S.top=S.base;
S.size=STACK_SIZE;
return OK;
}
//堆栈是否为空
Status StackEmpty(SqStack S){
if(S.top!=S.base) return ERROR;
return OK;
}
//进栈
Status Push(SqStack &S,Elem e){
if(S.top-S.base>=S.size){ //栈满,追加存储空间
S.base=(Elem *)realloc(S.base,(S.size+STACK_INC)*sizeof(Elem));
S.top=S.base+S.size;
S.size+=STACK_INC;
}
*S.top=e;
S.top+=1;
return OK;
}
//出栈
Status Pop(SqStack &S,Elem &e){
if(S.top==S.base) return ERROR;
S.top-=1;
e=*S.top;
return OK;
}
//括号匹配
Status Bracket(SqStack &S,char *str){
int i=0,flag1=0,flag2;
Elem e;
while(str[i]!='\0'){
switch(str[i]){
case '(':Push(S,'(');break; //'('进栈
case '[':Push(S,'[');break; //'['进栈
case ')':{Pop(S,e);
if(e!='(') flag1=1; break;} //出栈,判断是否为'('
case ']':{Pop(S,e);
if(e!='[') flag1=1;break;} //出栈,判断是否为'['
default: break;
}
if(flag1) break; //出现不匹配,立即结束循环
i++;
}
flag2=StackEmpty(S); //flag2判断堆栈是否为空
if(!flag1 && flag2) printf("括号匹配!\n");
else printf("括号不匹配!\n");
return OK;
}
//主函数
int main()
{
char temp,flag='y';
while(flag=='y'){
char str[255];
SqStack S;
printf("请输入字符串:");
scanf("%s",str);
scanf("%c",&temp); //接受输入的回车键
CreatStack(S);
Bracket(S,str);
cout<<"你想再试一次吗(按y继续): "<<endl;
scanf("%c",&flag);
printf("\n");
}
printf("程序结束.\n");
return 0;
}
-------------------------------------------------------------------