queue for max elem, pop, push

queue for max elem, pop, push

个人信息:就读于燕大本科软件工程专业 目前大三;

本人博客:google搜索“cqs_2012”即可;

个人爱好:酷爱数据结构和算法,希望将来从事算法工作为人民作出自己的贡献;

博客内容:queue for max elem, pop, push;

博客时间:2014-4-28;

编程语言:C++ ;

编程坏境:Windows 7 专业版 x64;

编程工具:vs2008 32位编译器;

制图工具:office 2010 ppt;

硬件信息:7G-3 笔记本;


my words

Don't let shorts beat you, because it doesn't worth.

problem

make a queue for max elem, pop and push.(problem from beauty from programming)

require fast for getting max elem

my solution

two stacks can make true a queue.

sub-problem 

getting max elem for the stack is so easy with dp.

my solution for my stack with max elem follows

name of type for elem is int

 

class Stack_mine
{
	// assume: the data length is not so long, its length <= the max number of int
	int * data ;
	int length;
	int * table;


public:

	// constructor function
	Stack_mine()
	{
		length = 0;
		data = new int[LENGTH];
		table = new int[LENGTH];
	}

	// function: pop
	int _pop()
	{
		if( ! _empty() )
		{
			length--;
			return data[length];
		}
		else 
		{
			cout<<"pop error"<<endl;
			return -1;
		}
	}
	
	// function: return length
	int _length( )
	{
		return length;
	}

	// function: push
	void _push(int a)
	{
		int * p1,*p2;
		if(length >= LENGTH)
		{
			p1 = (int *)realloc(data,LONGLENGTH * sizeof(int));
			p2 = (int *)realloc(table,LONGLENGTH * sizeof(int));
			data = p1;
			table = p2;
		}
		data[length] = a;
		if( length == 0 || data[ table[length-1] ] < a )
			table[length] = length;
		else table[length] = table[length-1];
		length ++;
	}

	// function: empty
	bool _empty()
	{
		if(length>0)
			return false;
		else return true;
	}

	// function: max
	int _max()
	{
		if(! _empty())
			return data[ table[ length-1 ] ];
		cout<<"error: empty stack for _max"<<endl;
		return -1;
	}
};

ok, my solution for queue max elem follows

class Queue_mine
{
	Stack_mine s1;
	Stack_mine s2;
public:
	Queue_mine(){};

	// function: push
	void _push(int a)
	{
		s1._push(a);	
	};

	// function: pop
	int _pop()
	{
		if(s2._empty())
		{
			while(!s1._empty())
			{
				s2._push(s1._pop());
			}	
		}
		return s2._pop();
	}

	// function: length
	int _length()
	{
		return s1._length() + s2._length();
	}

	bool _empty()
	{
		if( s1._empty() && s2._empty() )
		{
			return true ;
		}
		else return false ;
	}

	int _max()
	{
		if(! s1._empty() && ! s2._empty())
			return ( s1._max() > s2._max() ? s1._max() : s2._max() ); 
		else if( ! s1._empty() && s2._empty())
			return s1._max();
		else if( s1._empty() && ! s2._empty() )
			return s2._max();
		else {
			cout<<"empty for queue"<<endl;
			return -1;
		}
	}

};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值