/* stak; 1:创建栈顶标记指针 void init 2:元素入栈 void push 3:元素出栈 void pop 4:获取栈顶元素 top(返回值的类型为装入的数据的类型) 5:测定栈的元素数目 int size 6:栈判空 bool IsEmpty 7:栈清空 void DesTroy */
#include <iostream> using namespace std;
typedef struct node{ int value; struct node* pNext; }Node;
typedef struct stack{ int Count; Node *pTop; }Stack; /*创建新的节点*/ Node* CreateNode(int value) { Node* node = new Node; node->value = value; node->pNext = NULL; return node; } /*初始化栈*/ void init(Stack* &top) { if(top == NULL){ top = new Stack ; top->Count = 0; top->pTop = NULL; } return ; } /*元素入栈*/ void push(Stack* &top,Node* node) { if( top == NULL || node == NULL) return ; node->pNext = top->pTop; top->pTop = node; top->Count++; } /*元素弹出*/ void pop(Stack* &top){ if(top ->pTop == NULL || top == NULL ) return ; Node* del = top->pTop; top->pTop = del->pNext; top->Count--; delete del; del = NULL; } /*获取栈顶元素*/ Node* stacktop(Stack* top) { if(top == NULL || top->pTop == NULL) return NULL; return top->pTop; } /*测定栈内元素的数目*/ int size(Stack *top) { if(top == NULL) return 0; return top->Count; } /*栈判空*/ bool IsEmpty(Stack* top) { if (top == NULL) return true; return top->Count>0?0:1; } /*栈清空*/ void Destroy(Stack* top) { if(top == NULL) return ; while(top->Count){ pop(top); } }
int main() { Stack *top = NULL; /*初始化栈顶指针*/ init(top); int arr[] = {4,5,3,5,3,6,2}; Node* node = NULL; for(int i=0;i<sizeof(arr)/sizeof(int);i++){ /*创建节点*/ node = CreateNode(arr[i]); /*节点入栈*/ push(top,node); } /*获取栈的大小*/ int stacksize = size(top); cout<<"Stack size:"<<stacksize<<endl; /*获取栈顶元素*/ node = stacktop(top); cout<<"Stack top:"<< node->value<<endl; /*栈顶元素弹出*/ pop(top); stacksize = size(top); cout<<"Stack size:"<<stacksize<<endl; /*栈判空*/ bool empty = false; empty = IsEmpty(top); if(empty == true) { cout<<"stack is empty"<<endl; } else{ cout<<"stack is not empty"<<endl; } /*栈销毁*/ Destroy(top); empty = IsEmpty(top); if(empty == true) { cout<<"stack is empty"<<endl; } else{ cout<<"stack is not empty"<<endl; } system("pause"); return 0; }