栈是一种最基础的数据结构,是只允许在一端进行插入和删除的一种特殊的线性表。
当前栈:
入栈: 栈顶上移
出栈: 栈顶下移
以顺序表(数组)作为栈的储存结构: c++代码实现:
#include<iostream> using namespace std; const int MAXSIZE=1000; class stack //栈 { public: stack(){ //初始化 top=-1; } bool isFull(){ //判满 if(top==MAXSIZE-1){ return true; } return false; } bool isEmpty(){ //判空 if(top==0){ cout<<"stack is empty.\n"; return true; } return false; } bool push(int num){ //入栈 if(isFull()){ return false; } top++; data[top]=num; return true; } bool pop(){ //出栈 if(isEmpty()){ return false; } top--; return true; } int getTop(){ //取栈顶元素 if(!isEmpty()){ return data[top]; } } int getLength(){ //得到栈中元素个数 return top+1; } private: int top; //栈顶 int data[MAXSIZE]; //顺序表 };以结构体链表作为栈的储存结构: c++代码实现:
#include<iostream> using namespace std; struct node{ //栈的元素结点 int data; node *next; }; class stack //栈 { public: stack(){ //初始化栈 top=NULL; count=0; } ~stack(){ //析构栈 while(!isEmpty()){ pop(); } } bool isEmpty(){ //判空 if(top==NULL){ cout<<"stack is empty.\n"; return true; } return false; } void push(int num){ //入栈 if(isEmpty()){ node *newNode=new node; newNode->data=num; newNode->next=NULL; top=newNode; count++; return; } node *newNode=new node; newNode->data=num; newNode->next=top; top=newNode; count++; } bool pop(){ //出栈 if(isEmpty()){ return false; } node *n=top; top=top->next; count--; delete n; return true; } int getTop(){ //取栈顶元素 if(!isEmpty()){ return top->data; } } int getLength(){ //返回栈中元素个数 return count; } private: node *top; //栈顶 int count; //用来记录栈中元素个数 };