回 帖 发 新 帖 刷新版面

主题:多栈共享程序

//
//
//

#include <iostream.h>

class TStacks
{
public:
long numStacks;  //栈的个数
    long totSize;    // 总栈空间尺寸
    int  *room;      //栈空间
    int   *top,      //栈顶指针数组
          *bot ;     //栈底指针数组,记录的是偏移量
public:
TStacks(long m_numStacks,long m_totSize);
~TStacks();
void Push(int i,int x);        //将元素x进入第i号栈
int  Pop(int i);               //第i号栈元素出栈
void MoveStacks(int i);        //为第i号栈找空间
void Display();
};




回复列表 (共1个回复)

沙发

//
//
//

#include "TStacks.h"

TStacks::TStacks(long m_numStacks,long m_totSize)
{
numStacks=m_numStacks;
totSize=m_totSize;
room=new int[totSize];
for(int n=0;n<totSize;n++)
room[n]=0;
top=new int[numStacks];
bot=new int[numStacks+1];
for (int i=0;i<numStacks;i++)
{
bot[i]=i*totSize/numStacks;
top[i]=bot[i]-1;
}

bot[numStacks]=totSize;
}

void TStacks::MoveStacks(int i)
{
int r=i+1;
int l=i-1;
int choice=0;
int lLabel=1,rLabel=1;

////看看应该往哪边移
while(true)
{
if (r>=numStacks)
{
//cout<<"the right side no space!\n";
rLabel=0;
break;
}
else
{
if(bot[r+1]-(top[r]+1)>=1) break;
    else  ++r;
}
}

while(true)
{
if (l<0)
{
cout<<"the left side no space!\n";
            lLabel=0;
break;
}
else
{
if(bot[l+1]-top[l]>=1) break;
    else --l;
}
}

    //决定可不可以移,并且往哪边移
if(rLabel==0 &&lLabel==0)
{
cout<<"stack move fail!\n";
return;
}
else
{
if((rLabel!=0&&lLabel==0)||(rLabel!=0&&lLabel!=0&&((r-i)<=(i-l))))
choice=r;
else
choice=l;
}
           

    ////开始正式移栈

if (choice==r)
{
////向右移动栈
int oldTopr=top[r];
int temp=0;
while(true)
{
if (top[r]==top[i]) break;
else
{
temp=top[r];
room[++temp]=room[top[r]];
--top[r];
}
}

        ////处理应该处理的栈首和栈尾指针
int j=r;
top[r]=oldTopr+1;
while(true)
{
bot[j]++;
if ((j-1)<=i) break;
top[j-1]++;
j--;
}
}

    else
{
if (choice==l)
{
////移动栈
int oldBot=bot[l+1];
    int temp=0;
while(true)
{

if (bot[l+1]==top[i]+1) break;
                else
{
temp=bot[l+1];
room[--temp]=room[bot[l+1]];
    ++bot[l+1];
}
}

////处理该处理的指针
int j=l+1;
bot[l+1]=oldBot;
while(true)
{
bot[j]--;
if (j>i) break;
top[j]--;
j++;
}
}
}
}

void TStacks::Push(int i,int x)
{
  if(top[i]+1==bot[i+1])  MoveStacks(i);
room[top[i]+1]=x;
top[i]++;

}

int TStacks::Pop(int i)
{
return room[top[i]];
room[top[i]]=0;
top[i]--;
}

TStacks::~TStacks()
{
if (room!=NULL)
delete[] room;
}

void TStacks::Display()
{
for (int i=0;i<totSize;i++)
{
if(i%(totSize/numStacks)==0)   cout<<"    ";
cout<<room[i];
}
cout<<endl;
}




我来回复

您尚未登录,请登录后再回复。点此登录或注册