- 栈,分别用数组实现。栈 数组S,栈用一个标志位标志S.top.
Stack-empty(S)
if(S.top=0)
return true;
else return false ;
Push(S,x)
S.top=S.top+1
S[S.top]=x
Pop(S,x)
//判断栈下溢
S.top=S.top-1
return S[S.top+1]
队列:用两个标志位,Q.head,Q.tail;Q.head控制dequeue,Q.tail控制enqueue。
queue-empty(Q)
Q.head==Q.tail
return true
else return false
queue-full(Q)
if(Q.head==Q.tail+1||(Q.head==1&&Q.tail==Q.length)
return true
else return false
enqueue(Q,x)
if(queue-full(Q))
error "overflow"
Q[tail]=x;
if(Q.tail==Q.length)
Q.tail=1;
else
Q.tail+=1
dequeue(Q)
if queue-empty(Q)
error("underflow")
x=Q[head]
if Q.head==Q.length
Q.head=1;
else
Q.head=Q.head+1;
return
双向队列:
head-enqueue(Q,x)
if queue-full(Q)
error "overflow"
if Q.head==1
Q.head=Q.length;
else
Q.head==Q.head-1;
queue.head=x;
tail-enqueue(Q,x)
if queue-full(Q)
error "overflow"
else
Q[Q.tail]=x;
if Q.tail==Q.length
Q.tail=1;
else
Q.tail=Q.tail+1;
head-dequeue(Q)
if queue-empty(Q)
error "downflow"
else
x=Q[Q.head]
if Q.head==Q.length
Q.head=1;
else
Q.head=Q.head+1
return x;
tail-dequeue(Q)
if queue-empty(Q)
error "downflow"
else
if Q.tail=1
Q.tail=Q.length
else Q.tail = Q.tail-1;
x=Q[Q.tail]
return x
如何使用两个栈实现一个队列?
一个栈S1负责存储enqueue,一个栈S2负责dequeue,enqueue:直接入S1,出栈的时候,判断S2是否为空,空的话,需要把S1的元素一个一个出栈并入栈S2,使S1清空。不为空的话,直接从S2出栈。
如何使用两个队列实现一个栈?
PUSH,向活跃的队列入队。
POP,将当前活跃的队列的元素一个一个出队列,并入另外的队列,最后一个元素为pop的元素。这时候需要更换活跃的队列