栈和队列

来源:互联网 发布:淘宝让你提供质检报告 编辑:程序博客网 时间:2024/06/01 20:47

一、栈:

是限定仅在表尾进行插入和删除操作的线性表,允许插入和删除的一端称为栈顶,另一端称为栈底,不含任何数据元素的栈称为空栈。

栈具有先进后出的特性。

顺序栈:
1、顺序栈入栈算法Push:
template<class DataType>

void SeqStack<DataType>::Push (DataType x)

{
if(top==StackSize-1)throw"上溢";

data[++top]=x;

}
2、顺序栈出栈算法Pop:
templae <class DataType>

DataType SeqStack<DataType>::Pop;

{
if(top==-1)throw"下溢";

x=data[top--];

return x;

}
3、两栈共享空间入栈算法Push:
template <class DataType>

void BothStack<DataType>::Push(int i,DataType x)

{
if(top1==top2-1)throw'上溢';

if(i==1)data[++top]=x;

if(i==2)data[--top]=x;

}
4、两栈共享空间出栈算法Pop:
template <class DataType>

DataType BothStack<DataType>::Pop(int i)

{
if(i==1){
if(top==-1)throw"下溢";

return data[top1--];

}
if(i==2){
if(top==StackSize)throw"下溢";

return data[top2++];

}
}
5、链栈入栈算法Push:
template <class DataType>

void LinkStack<DataType>::Push(DataType x)

{
s=new Node;s->data=x;

s->next=top;top=s;

}

6、链栈出战算法Pop:
template <class DataType>

DataType LinkStack<DataType>::Pop()

{
if(top==NULL)throw'下溢';

x=top->data;p=top;

top=top->next;

delete p;

return x;

}

二、队列:

队列是只允许在一端进行插入操作,在另一端进行删除操作的线性表。

队列具有先进后出的特性。

循环对列入队算法EnQueue:
template <class DataType>

void CirQueue<DataType>::EnQueue(DataType x)

{
if((rear+1)%QueueSize==front)throw"上溢";

rear=(rear+1)%QueueSize;

data[rear]=x;

}

1、循环队列出队算法DeQueue:
template <class DataType>

DtaType CirQueue<DataType>::DeQueue()
{
if(rear==front)throw""下溢;

front=(front+1)%QueueSize;

return data[front];

}
2、读取队头元素算法GetQueue:
template<class DataType>

DataType CirQueue<DataType>::GetQueue()
{
if(rear==front)throw"下溢";

i=(front+1)%QueueSize;

return data[i];

}
3、链队列构造函数算法LinkQueue:
template <class DataType>

LinkQueue<DataType>::LinkQueue()
{
s=new Node;s->next=NULL;

front =rear=s;

}
4、链队列入队算法EnQueue:

template <class DataType>

void LinkQueue<DataType>::EnQueue(DataType x)

{
s=new Node; s->data=x;

s->next=NULL;

rear->next=s;

rear=s;

}

5、链队列出队算法:

template <class DataType>

DataType LitnkQueue<DataType>::DeQueue()
{
if(rear==front)throw"下溢";

p=front ->next;x=p->data;

front->next=p->next;

if(p->next==NULL)rear=front;

delete p;

return x;

}

 

 

 

0 0
原创粉丝点击