猿问

偽代碼和C++的轉換

设从键盘输入一整数的序列:a1,a2,a3,..,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将aⅰ进栈;当aⅰ=-1时,输出栈顶整数并出栈。算法应对异常情况(入栈满等)给出相应的信息。
请分别用伪代码和C++完成。

慕用3498290
浏览 1111回答 1
1回答

Sival_Eulyn

伪代码:while getEleFromStream -> ele  if ele != -1    if fullStack      logout    else      push ele  else    if emptyStack      logout    else      print popC++:#include <stack>#include <iostream>using namespace std;typedef stack<int> Stack;const int stack_limit = 20;void logout(const char *info);int getEleFromStream(Stack &stk); // return errno_t [0 == normal, 1 == full, -1 == empty]                                                        // process will exit while the empty condition take placeint main(){  Stack stk;  while (getEleFromStream(stk) != -1);  return 0;}void logout(const char *info){  cout << info << endl;}int getEleFromStream(Stack &stk){  int ele = 0;  cin >> ele;  if (ele != -1)    if (stk.size() == limit)    {      logout("Full Stack!");      return 1;    } else      stk.push_back(ele);  else    if (stk.size() == 0)    {      logout("Empty Stack!");      return -1;    } else      cout << stk.pop() << endl;  return 0;}
随时随地看视频慕课网APP

相关分类

数据结构
我要回答