PhoenixZq
分享是一门艺术~~

设计包含min函数的栈。
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
要求函数min、push以及pop的时间复杂度都是O(1)。

理解:

1.建立两个顺序栈A,B。

A:依次push输入的节点;

B:每次向push节点的同时,向B中pushA中的最小值。

比如:

A     B

2     2

4     2

6     2

1     1   

3     1

5     1

/*
 * micro3.h
 *
 *  Created on: 2011-3-13
 *      Author: zq
 */

#ifndef MICRO3_H_
#define MICRO3_H_
class SqStack{
public:
	int *base;
	int *top;
	//int length;
	int stacksize;
	SqStack(int *b=0,int *t=0,int l=0,int size=50):
		base(b),top(t),stacksize(size){
		base = new int[stacksize];
		top = base;
	}
	~SqStack(){
		delete []base;
	}
	int Push(int data);
	int Pop();
};

#endif /* MICRO3_H_ */

/*
 * micro3.cpp
 *
 *  Created on: 2011-3-13
 *      Author: zq
 */
#include <iostream>
#include "micro3.h"
using namespace std;

int SqStack::Push(const int newdata){
	//if(top-base >= stacksize)
	*++top = newdata;
	//++length;
	return 0;
}

int SqStack::Pop(){
	if (top == base) return NULL;
	int data = *top--;
	//--length;
	return data;
}

int main(){
	SqStack S,minS;
	int data;
	cout << "输入数据: " <<endl;
	cin >> data;
	while(data != 9999){
		S.Push(data);
		if (minS.top == NULL ||*minS.top > data)
			minS.Push(data);
		else minS.Push(*minS.top);
		cin >> data;
	}
	//cout << "S.length: " <<S.length << endl;
	int length = S.top-S.base;
	cout << "S.length: " <<length << endl;

	for (int i = 1;i <= length;i++){
		cout << "显示第"<< i <<"次出栈数据"<< S.Pop() << endl;
		cout << "显示第"<< i <<"次出栈前栈中最小值: " << minS.Pop() << endl;
	}

	return 0;
}

posted on 2011-03-17 13:03  PhoenixZq  阅读(222)  评论(0编辑  收藏  举报