设计包含min函数的栈。
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
cpp通过 冒泡排序检查最小值 和 stack.getmin 比较。
定义栈的数据结构,要求添加一个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;
}
};
#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 比较。
![](http://www.000webhost.com/images/banners/120x60/banner1.gif)