我无法理解 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
请帮助我理解这一点。