我无法理解push和pop如何与堆栈一起工作。我明白他们是如何工作的,因为他们推动一个号码让我们说到堆栈上,并且推出的最后一个号码将被弹出。我也理解指针背后的逻辑以及它们如何工作。我不明白的是代码应该如何编写。堆栈实现
我的程序应该让用户创建一个堆栈(确定它的大小),然后选择将堆栈中的内存(数字)推出或弹出。
这是我到目前为止,我卡住了。我已经通过cplusplus.com进行了研究,并阅读了关于这些东西的几乎所有内容,但仍然无法弄清楚该程序应该如何布置以及如何运行。
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
int choice;
int * arrPtr = NULL;
int * stack;
int * top;
int val, capacity, size;
//stack would point to the location of the first element,
// top would point to the location where the next element will be stored,
// capacity is the number of elements that can be stored in the stack,
// size would be the number of elements actually stored in the stack
int main()
{
//This is the menu
cout << "1. Create" << endl;
cout << "2. Push" << endl;
cout << "3. Pop" << endl;
cout << "4. Count" << endl;
cout << "5. Display" << endl;
cout << "6. Exit\n" << endl;
cin >> choice;
//I figured i would use choices for the menu and went ahead and wrote it out
switch(choice)
{
case 1:
create();
break;
case 2:
push();
break;
case 3:
pop();
break;
case 4:
count(0);
break;
case 5:
display();
break;
case 6:
exit();
default:
cout << "Please enter correct choice (1-4)!";
break;
}
return 0;
} //end main
void create()
{
cout << "Enter the size of the stack you wish to create: ";
int capacity = 0;
cin >> capacity;
arrPtr = new int[capacity];
} //end create function
//From here it went wrong, I cannot figure it out.
void push(){
for (int i = 0; i < capacity; i++)
{
cout << "Enter the number you wish to put on the stack: ";
cin >> val;
push(val)
}//end for
}//end push
请帮我理解这一点。
您使用动态内存分配进行堆栈实现的具体原因是什么? – Subhajit 2013-02-10 18:45:25
用户应该创建堆栈大小 – user2057825 2013-02-11 07:12:22