以下是引用片段:
#include
using namespace std;
#define MAX 10 // MAXIMUM STACK CONTENT
class stack
{
private:
int arr[MAX]; // Contains all the Data
int top; //Contains location of Topmost Data pushed onto Stack
public:
stack() //Constructor
{
top=-1; //Sets the Top Location to -1 indicating an empty stack
}
void push(int a) // Push ie. Add Value Function
{
top++; // increment to by 1
if(top
{
arr[top]=a; //If Stack is Vacant store Value in Array
}
else
{
cout<<"STACK FULL!!"<
top--;
}
}
int pop() // Delete Item. Returns the deleted item
{
if(top==-1)
{
cout<<"STACK IS EMPTY!!!"<
return NULL;
}
else
{
int data=arr[top]; //Set Topmost Value in data
arr[top]=NULL; //Set Original Location to NULL
top--; // Decrement top by 1
return data; // Return deleted item
}
}
};
int main()
{
stack a;
a.push(3);
cout<<"3 is Pushed\n";
a.push(10);
cout<<"10 is Pushed\n";
a.push(1);
cout<<"1 is Pushed\n\n";
cout<
cout<
cout<
return 0;
}
输出为:
3 is Pushed
10 is Pushed
1 is Pushed
1 is Popped
10 is Popped
3 is Popped
我们可以很清楚的看到最后入栈的数据第一个出栈。这就是为什么堆栈被成为LIFO(后进先出,Last In First Out)。我猜你也明白为什么了。
让我们看看如何编译、执行此程序的。我们首先创建一个叫top的变量,使它处在栈顶位置。赋值-1,表示堆栈是空的。当有数据输入,top自动加1,并把数据存入arr数组中。对于这个数据结构有一个缺点。我们最多只能放10个元素。