Exemplo n.º 1
0
void main()
{ SElemType e;
  SqStack *Sa;
  clrscr();
  cout<<"stackmain.cpp运行结果:\n";
  Sa->InitStack(&Sa);
  strcpy(e.name,"stu1");
  strcpy(e.stuno,"100001");
  e.age=20;
  e.score=87;
  cout<<"现在栈是空栈!\n";
  cout<<"现在调用压栈函数!\n";
  Sa->Push(e);
  cout<<"现在栈有一个元素!\n";
  StackPrintElem(&Sa->GetTop());
  if(Sa->StackEmpty()) cout<<"栈Sa空!\n";
  else cout<<"栈Sa非空!\n";
  strcpy(e.name,"stu3");
  strcpy(e.stuno,"100002");
  e.age=21;
  e.score=90;
  Sa->Push(e);
  cout<<"现在栈有二个元素!\n";
  StackPrintElem(&e);
  cout<<"栈Sa的长度:"<<Sa->StackLength()<<endl;
  cout<<"现在将元素e弹出栈!\n";
  Sa->Pop(&e);
  StackPrintElem(&e);
  cout<<"栈的剩余元素:\n";
  Sa->StackTraverse(StackPrintElem);
  if(Sa->StackEmpty()) cout<<"栈Sa空!\n";
  else cout<<"栈Sa非空!\n";
  getch();
}
Exemplo n.º 2
0
double EvaExpression()
{
	SqStack<int> OPTR;
	SqStack<double> OPND;
	
	int buffer;
	bool preIsDigit = false;
	bool hasDot = false; 
	int exp;
	
	double ans = 0;
	
	OPTR.Push(Index('#'));
	
	buffer = mGetchar();
	if (buffer == INPUT_VALID) return EvaExpression();

	while (buffer!='#' || OPTR.GetTop()!=Index('#'))
	{
		if (buffer == '.')
		{
			if (hasDot)
			{
				char tmp_s[1024];
				printf("您的输入有误,请确保输入的算术表达式合法!\n");
				if (buffer != '\n') gets(tmp_s);
				return EvaExpression();
			}
			hasDot = true;
			exp = 0;
			
			buffer = mGetchar();
			if (buffer == INPUT_VALID) return EvaExpression();
		}
		else if (In(buffer, DIGIT)) 
		{
			if (preIsDigit)
			{
				double number; 
				OPND.Pop(&number);
				
				if (hasDot)
				{
					exp--;
					number += E(buffer-'0', exp);
				}
				else
				{
					number *= 10;
					number += buffer-'0';
				}
				OPND.Push(number);
			}
			else
			{
				OPND.Push(buffer-'0');
				preIsDigit = true; 
			}
			
			buffer = mGetchar();
			if (buffer == INPUT_VALID) return EvaExpression();
		}
		else 
		{
			int toOperate, top;
			preIsDigit = false;
			hasDot = false;
			toOperate = Index(buffer);
			top = OPTR.GetTop();
			switch(cmp[top][toOperate])
			{
				case -1:
					OPTR.Push(toOperate);
					buffer = mGetchar();
					if (buffer == INPUT_VALID) return EvaExpression();
					break;
				case 0:
					int tmp;
					OPTR.Pop(&tmp);
					buffer = mGetchar();
					if (buffer == INPUT_VALID) return EvaExpression();
					break;
				case 1:
					int op;
					double a, b;
					if (OPTR.Pop(&op) != OK || OPND.Pop(&b) != OK || OPND.Pop(&a) != OK)
					{
						char tmp_s[1024];
						printf("您的输入有误,请确保输入的算术表达式合法!\n");
						if (buffer != '\n') gets(tmp_s);
						return EvaExpression();
					}
					ans = Operate(a, op, b);  
					OPND.Push(ans);
					break;
				case ERROR:
					char tmp_s[1024];
					printf("您的输入有误,请确保输入的算术表达式合法!\n");
					if (buffer != '\n') gets(tmp_s);
					return EvaExpression();
				default:
					exit(ERROR);
			}
		}
		
	}
	OPND.Pop(&ans);
	if (OPTR.IsEmpty() || OPND.IsEmpty() ) return ans;
	
	char tmp_s[1024];
	printf("您的输入有误,请确保输入的算术表达式合法!\n");
	if (buffer != '\n') gets(tmp_s);
	return EvaExpression();
}