《微软面试题》设计包含min函数的栈

设计包含min函数的栈。
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。

要求函数min、push以及pop的时间复杂度都是O(1)。

代码如下:


stack.h

#pragma once

#include <assert.h>
//simulation stack DataStruct

template<typename T>
class Node 
{
public:

	Node(T t)
	{
		data = t;
		pre = NULL;
	}
	T data;
	Node * pre;

	bool operator >(const T & t)
	{
		if (data >= t.data)
		{
			return true;
		}

		return false;
	}
};

template<typename T>
class Stack
{
public:

	Stack()
	{
		cur = NULL;
		//pre = NULL;
	}

	Node<T> * cur;

	void pushback(Node<T> * node)
	{
		node->pre = cur;
		Node<T> * tmp = cur;
		cur = node;
		cur->pre = tmp;
	}
	void popback()
	{
		Node<T> * tmp = cur->pre->pre;
		cur = cur->pre;
		cur->pre = tmp;
	}

	Node<T> * min(int destMin)
	{
		while(cur == NULL || cur->pre != NULL)
		{
			if (cur->data >= cur->pre->data)
			{
				cur =cur->pre;
			}
			else
			{
				cur->pre = cur->pre->pre;
			}
		}

		assert(cur != NULL);

		if (cur->data != destMin)
		{
			assert(0);
		}

		return cur;
	}
};


man.cpp

#include "stack.h"

#include "stdlib.h"

#include <time.h>

typedef Node<int> _node;
typedef Stack<int> _stack;

int GetMin(int *num,int len)
{
	for (int i=0;i<len;i++)
	{
		for (int j=len-1;j>i;j--)
		{
			if (num[i] > num[j])
			{
				int tmp = num[i];
				num[i] = num[j];
				num[j] = tmp;
			}
		}
	}

	return num[0];
}

int _tmain(int argc, _TCHAR* argv[])
{
	_stack mystack;

	srand(time(NULL));

	//int a[10]={0};

	int a[10]={6,1,27,60,24,56,57,58,90,87};

	for (int i=0;i<10;i++)
	{
		int tmp = rand()%100;//(i+10)%3;
		//int tmp = a[i];

		_node * p = new _node(tmp);

		printf("%d,",tmp);

		a[i] = tmp;

		mystack.pushback(p);
	}

	//use pop check min

	int _min = GetMin(a,10);

	//printf("\ndest min=%d\n",_min);

	_node * p = mystack.min(_min);

	if (p != NULL)
	{
		printf("\nmin node.data=%d\n",p->data);
	}

	assert(_min == p->data);

	getchar();

	return 0;
}

cpp通过 冒泡排序检查最小值 和 stack.getmin 比较。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值