zoukankan      html  css  js  c++  java
  • 第十章:基本数据结构(0)

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

    Stack  A,B  //A用于插入,B用于删除

    ENQUEUE(Q,x)

    if top[A]==n

      then error "upflow"

      else  top[A]=top[A]+1

         A[top[A]] <- x

    DEQUEUE(Q,x)

    if STACK-EMPTY(B)

      if STACK-EMPTY(A)

         error "underflow"

       else  

        while top[A]!=0

          PUSH(B,POP(A))

         POP(B)

    else

      POP(B)

    #include <iostream>
    #include <string>
    #include "stack.h"
    
    using namespace std;
    
    #define    STACK_SIZE	20
    #define    QUEUE_SIZE	50
    
    struct Stack{
    	int count;
    	int list[STACK_SIZE];
    };
    
    struct Queue{
    	int head,tail;
    	int list[QUEUE_SIZE];
    };
    
    void push(Stack *s,int x){
    	if (s->count!=STACK_SIZE){
    		s->list[(s->count)++]=x;
    	}else{
    		cout<<"upflow"<<endl;
    	}
    }
    
    int pop(Stack *s){
    	if (s->	count!=0){
    		return s->list[--(s->count)];
    	}else{
    		cout<<"underflow"<<endl;
    		return NULL;
    	}
    }
    
    bool empty_stack(Stack *s){
    	return s->count==0? true:false;
    }
    
    void enqueue(Stack *s1,Stack *s2,int x){
    	if (s1->count==STACK_SIZE){
    		cout<<"upflow"<<endl;
    		return ;
    	}else{
    		push(s1,x);
    	}
    }
    
    int dequeue(Stack *s1,Stack *s2){
    	if (empty_stack(s2)){
    		while (s1->count!=0){
    			push(s2,pop(s1));
    		}
    		return pop(s2);
    	}else{
    		return pop(s2);
    	}
    }
    

      

      

  • 相关阅读:
    解决phpmailer可以在windows下面发送成功, 在linux下面失败的问题
    centos安装svn
    linux下面配置安装nodejs+npm
    排序与搜索
    链表
    栈和队列
    顺序表
    初识算法、数据结构
    Linux_02
    Linux_01
  • 原文地址:https://www.cnblogs.com/lsf90/p/3143726.html
Copyright © 2011-2022 走看看