开发一个下堆栈实现,禁止重复,采用"旧项遗忘"策略,其中的项为0-M-1的整数,而且让push和pop运算时间恒定(以下是实现算法)
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#define maxN 100
typedef struct LNode
{
int data;
struct LNode *prior;
struct LNode *next;
}LNode,*LinkList;
typedef struct Mark
{
int data;
struct LNode *current;
}Mark;
static LinkList head,temp; //head是头结点,temp是指示指针
static Mark t[maxN];
void STACKinit( )
{
head=(LinkList)malloc(sizeof(LNode)); //建立头结点
head->next=NULL;
temp=head;
for(int i=0;i<maxN;i++) //初始化标志t[maxN]数组
{
t[i].data=0;
t[i].current=NULL;
}
}
bool STACKempty()
{
if(head==temp)
return true;
else
return false;
}
void STACKpush(int item)
{
if(t[item].data==0)
{
temp->next=(LinkList)malloc(sizeof(LNode));
temp->next->prior=temp;
temp=temp->next;
temp->data=item;
temp->next=NULL; //建立数据为item的值的结点
t[item].data=1;
t[item].current=temp; //改变标志数组的值
}
else
{
t[item].current->prior->next=t[item].current->next;
t[item].current->next->prior=t[item].current->prior; //断掉结点t[item].current
temp->next=t[item].current;
t[item].current->prior=temp;
t[item].current->next=NULL;
temp=t[item].current; //把结点t[item];连接到双链表的最后
}
}
int STACKpop()
{
int e=temp->data;
temp=temp->prior;
temp->next=NULL;
t[e].data=0;
t[e].current=NULL; //改变标志数组
return e;
}
void print()
{
while(!STACKempty())
{
printf("%d/n",STACKpop());
}
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("最大输入值为99,请勿超过!/n");
STACKinit();
STACKpush(5);
STACKpush(6);
STACKpush(7);
STACKpush(8);
STACKpush(5);
STACKpush(6);
print();
return 0;
}