定义栈的数据结构并实现操作,要求编写一个函数min,能够得到栈的最小元素。同时要求函数min、push和pop的时间复杂度都是O(1)。
解题思路:
通过遍历栈来寻找最小元素的时间复杂度为O(n),要想时间复杂度降为O(1),就要牺牲空间,创建另一个栈进行同步操作。
- 创建两个栈,栈顶元素分别为stackTop和minStackTop(以栈顶名称代替栈的名称)。其中stackTop栈进行正常的入栈、出栈操作。
- stackTop栈入栈时,如果stackTop栈为空,则stackTop栈和minStackTop都入栈elem元素;如果入栈元素elem比minStackTop栈顶元素小,则在stackTop入栈后,把入栈元素elem也加入到minStackTop栈顶(保证minStackTop记录stackTop当前所有元素中的最小值)。
- 如果入栈元素elem比minStackTop栈顶元素大,此情况说明入栈elem后stackTop中最小值没有变。此时minStackTop仍然需要入栈一个元素,这个元素的大小等于当前minStackTop的栈顶元素。
程序输出结果如下:
完整代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int Elem;
typedef struct tagNode
{
Elem data;
struct tagNode *next;
}Node;
Node *stackTop,*minStackTop;
int stackLength;
/*创建*/
bool stackCreate()
{
stackLength = 0;
stackTop = NULL;
minStackTop = NULL;
return true;
}
/*入栈*/
bool stackPush(const Elem &it)
{
Node *temp,*mintemp;
temp = (Node *)malloc(sizeof(Node));
mintemp = (Node *)malloc(sizeof(Node));
if (temp == NULL || mintemp == NULL)
return false;
if (stackLength == 0)
{
temp->data = it; mintemp->data = it; //stackTop和minStackTOP同时入栈
temp->next = stackTop; mintemp->next = minStackTop;
stackTop = temp; minStackTop = mintemp;
}
else
{
temp->data = it;
temp->next = stackTop;
stackTop = temp;
if (it < minStackTop->data) //入栈的元素比minStackTop栈顶元素小
{
mintemp->data = it;
mintemp->next = minStackTop;
minStackTop = mintemp;
}
else //入栈的元素大于或等于minStackTop栈顶元素
{
mintemp->data = minStackTop->data;
mintemp->next = minStackTop;
minStackTop = mintemp;
}
}
stackLength++;
return true;
}
/*出栈*/
bool stackPop(Elem &it)
{
Node *temp, *mintemp;
if (stackLength == 0)
return false;
it = stackTop->data;
temp = stackTop->next;
free(stackTop);
stackTop = temp;
/*minStackTop出栈*/
mintemp = minStackTop->next;
free(minStackTop);
minStackTop = mintemp;
stackLength--;
return true;
}
int min()
{
return minStackTop->data;
}
void main()
{
Elem elem;
int i;
int x;
srand(unsigned(time(NULL)));
x = 1 + (rand() % 20); //产生一个1-20的随机数,作为栈的元素个数
stackCreate();
printf("入栈:");
for (i = 0; i < x; i++)
{
elem = rand() % 100;
stackPush(elem);
printf("%d ", elem);
}
/*以上代码产生了一个元素个数不确定的栈以供测试*/
printf("\n最小元素:%d\n", min());
}