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);
    	}
    }
    

      

      

  • 相关阅读:
    centos 7.5 snmp 安装
    centos 7.5 telnet 离线安装
    使用httpClient发送请求(支持https)
    kafka基本概念
    List根据时间字符串排序
    mac安装yosys遇到`dyld: malformed mach-o image`报错
    ctags的--exclude选项
    每周分享(3)
    实践OKR极易出现的四大误区
    从OKR小白到成功落地OKR(三)
  • 原文地址:https://www.cnblogs.com/lsf90/p/3143726.html
Copyright © 2011-2022 走看看