第十章:基本数据结构(1)

10.1-7  说明如何用两个队列来实现一个栈,并分析有关栈操作的运行时间。

QUEUE A,B

PUSH(S,x)

if A正在使用

  if tail[A]+1=head[A]

    error "upflow"

  else

    ENQUEUE(A,x)

else

  if tail[B]+1=head[B]

    error "upflow"

  else

    ENQUEUE(B,x)

POP(S)

if A正在使用

  if QUEUE_EMPTY(A)

    error "underflow"

  else

    while head[A]+1!=tail[A]

      ENQUEUE(B,DEQUEUE(A))

    return DEQUEUE(A)

else

  if QUEUE_EMPTY(B)

    error "underflow"

  else

    while head[B]+1!=tail[B]

      ENQUEUE(A,DEQUEUE(B))

    return DEQUEUE(B)

#include <iostream>
#include <string>

#define    QUEUE_SIZE    50

using namespace std;

struct Queue{
    int head,tail;
    int list[QUEUE_SIZE];
};

bool empty_queue(Queue *q){
    return q->tail==q->head;
}

void enqueue(Queue *q,int x){
    if ((q->tail+1)%QUEUE_SIZE==q->head){
        cout<<"upflow"<<endl;
    }else{
        q->list[(q->tail++)%QUEUE_SIZE]=x;
    }
}

int dequeue(Queue *q){
    if (empty_queue(q)){
        cout<<"underflow"<<endl;
        return NULL;
    }else{
        return q->list[(q->head++)%QUEUE_SIZE];
    }
}

void push(Queue *q1,Queue *q2,int x){
    if (empty_queue(q1)){
        enqueue(q2,x);
    }else{
        enqueue(q1,x);
    }
}

int pop(Queue *q1,Queue *q2){
	if (empty_queue(q1)){
		while (q2->tail!=(q2->head+1)){
			enqueue(q1,dequeue(q2));
		}
		return dequeue(q2);
	}else{
		while (q1->tail!=(q1->head+1)){
			enqueue(q2,dequeue(q1));
		}
		return dequeue(q1);
	}
}

  

  

原文地址:https://www.cnblogs.com/lsf90/p/3143780.html