码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象第四次实验参考代码

时间:2015-11-08 19:30:24      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!