标签:
#include <iostream.h> #include <stdlib.h> #include <time.h> #define NULL 0 struct SNode{ int data; //data domain SNode *next; //pointer domain }; class Stack{ public: Stack(); ~Stack(); void Push(int e); //insert a data into stack int Pop(); //delete a data from stack int GetTop(); //Get the data of Stack Top int Empty(); //Judge the Stack empty or not friend int GetSum(); //get sum of stack,friend function //friend class getsum; // get sum of stack,friend class static int num; //static number private: SNode *Head; //head node }; int Stack::num = 0; //initialize static number Stack::Stack() { Head = new SNode; Head->next = NULL; } Stack::~Stack() { delete Head; //here,should delete every node of link table using loop } void Stack::Push(int e) { SNode *p,*q; if(!(p = new SNode)) exit(0); p->data = e; q = Head; while(q->next) q = q->next; q->next = p; p->next = NULL; num++; } int Stack::Empty() { return !num; } int Stack::Pop() { int e; if(Empty()) { cout<<"The Stack is empty!"<<endl; exit(0); } SNode *p,*q; p = Head; q = p; while(p->next) { q = p->next; if(!q->next) break; p = p->next; } p->next = NULL; e = q->data; delete q; num--; return e; } int Stack::GetTop() { int e; if(Empty()) { cout<<"The Stack is empty!"<<endl; exit(0); } SNode *p; p = Head; while(p->next) { p = p->next; } e = p->data; return e; } int GetSum(Stack &a) { int sum = 0,m,tmp; m = a.num; cout<<endl<<"Pop Stack List is:"<<endl; for(int i = 0;i<m;i++) { tmp = a.Pop(); cout<<" "<<tmp; sum+ = tmp; } cout<<endl; return sum; } void main() { Stack s; int temp; srand((unsigned)time(NULL)); cout<<"Push List is:"<<endl; for(int i = 1;i< = 100;i++) { temp = rand()%1000; if(s.Empty()||temp > s.GetTop()) { cout<<" "<<temp; s.Push(temp); } if(s.GetTop()> = 999) break; } cout<<endl<<"SUM is:"<<GetSum(s)<<endl; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/laoduan_78/article/details/49719465