旧项遗忘

开发一个下堆栈实现,禁止重复,采用"旧项遗忘"策略,其中的项为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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值