//用数组实现栈结构
#include<iostream>
#include<string>
using namespace std;
void push(int *stack, int num, int &index, int stack_len)
{
if (index >= stack_len - 1)
cout << "the stack is enough, please pop the data!" << endl;
else
{
++index;
stack[index] = num;
}
}
void pop(int *stack, int &index)
{
if (index < 0)
cout << "the stack is empty, please push the data!" << endl;
else
{
cout << endl << '\t' <<stack[index];
--index;
}
}
void peak(int *stack, int &index)
{
if (index < 0)
cout << "the stack is empty, please push the data!" << endl;
else
{
cout << endl << '\t' <<stack[index];
}
}
void show(int *stack, int &index)
{
if (index < 0)
cout << "the stack is empty, please push the data!" << endl;
else
{
for (int i = index; i >= 0; i--)
cout << endl << '\t' <<stack[i];
}
}
int main()
{
int stack_len, num;
cout << "please input the length of the stack:" << '\t';
cin >> stack_len;
int *stack = new int [stack_len];
int index = -1;
string str;
cout << endl << "input data. please select the method: push pop peak show exit: " << '\t';
while(cin >> str)
{
cout << endl;
if(str == "push")
{
cout << "please input the data: " << '\t';
cin >> num;
push(stack ,num , index, stack_len);
}
else if(str == "pop")
pop(stack, index);
else if(str == "peak")
peak(stack, index);
else if(str == "show")
show(stack, index);
else if(str == "exit")
{
delete [] stack;
return 0;
}
else
cout << "try again" << endl;
cout << endl << "input data. please select the method: push pop peak exit: " << '\t';
}
system("pause");
return 0;
}
用数组实现栈结构
猜你喜欢
转载自blog.csdn.net/Cris_7/article/details/82849510
今日推荐
周排行