要求函数min、push以及pop的时间复杂度都是O(1)。
栈用链表实现,主要思想是增加一个辅助链表栈,存储最小元素。
//stack.h
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef Node* Link;
struct Node
{
int data;
Link next;
};
struct Stack
{
Link pHead;
Link pMinHead;
};
void CreateStack(Stack& S);
void Push(Stack& S,int element);
void Pop(Stack& S);
int IsEmpty(Stack S);
void Destory(Stack& S);
void Print(Stack S);
int FindMin(Stack S);
//stack.cpp
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
void CreateStack(Stack& S)
{
S.pMinHead=NULL;
S.pHead=NULL;
}
void Push(Stack& S,int element)
{
Link newnode;
newnode=(Link)malloc(sizeof(Node));
if(newnode==NULL)
{
printf("out of space\n");
return;
}
newnode->data=element;
newnode->next=S.pHead;
S.pHead=newnode;
if(S.pMinHead==NULL || S.pMinHead->data>element)
{
Link minnode;
minnode=(Link)malloc(sizeof(Node));
if(minnode==NULL)
{
printf("out of space\n");
return;
}
minnode->data=element;
minnode->next=S.pMinHead;
S.pMinHead=minnode;
}
}
void Pop(Stack& S)
{
if(IsEmpty(S))
{
printf("the stack is empty\n");
return;
}
Link temp;
temp=S.pHead;
if(S.pHead->data==S.pMinHead->data)
{
Link mintemp;
mintemp=S.pMinHead;
S.pMinHead=S.pMinHead->next;
free(mintemp);
}
S.pHead=S.pHead->next;
free(temp);
}
int IsEmpty(Stack S)
{
if(S.pHead==NULL)
return 1;
else
return 0;
}
void Destory(Stack& S)
{
Link temp;
while(S.pHead!=NULL)
{
temp=S.pHead;
S.pHead=S.pHead->next;
free(temp);
}
}
void Print(Stack S)
{
Link temp=S.pHead;
if(!IsEmpty(S))
{
while(temp)
{
printf("%d",temp->data);
temp=temp->next;
}
}
printf("\n");
printf("min\n");
temp=S.pMinHead;
while(temp)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("\n");
}
int FindMin(Stack S)
{
if(S.pMinHead)
return S.pMinHead->data;
else return 0;
}
//main.cpp
#include<stdio.h>
#include<iostream>
#include"stack.h"
int main()
{
Stack S;
CreateStack(S);
Push(S,5);
Push(S,3);
Push(S,7);
Print(S);
printf("%d\n",FindMin(S));
Push(S,2);
Print(S);
printf("%d\n",FindMin(S));
Pop(S);
Print(S);
printf("%d\n",FindMin(S));
Push(S,8);
Push(S,1);
Print(S);
printf("%d\n",FindMin(S));
return 0;
}
输出:
735
min
35
3
2735
min
235
2
735
min
35
3
18735
min
135
1
请按任意键继续. . .