jake1036

队列和栈的基本操作

                              队列和栈的基本操作

     栈的操作,栈是一种先进后出的操作,需要注意的是栈的满与空,栈空的情况是 top == 0 ,栈满的情况是 top == N 。
     栈实现的代码如下:
    

#include<iostream>
 
using namespace std ;
 
const int N = 100 ;
 
struct Stack
 
{
    
int a [N] ;    
    
int top    ;    
 }
 ;
 
 
 
void iniStack(Stack *stack) ;
 
bool empty(Stack *stack) ;
 
void push(Stack *stack , int x) ;
 
int pop(Stack *stack ) ;
 
bool full(Stack * stack) ;
 
 
int main()
 
{
    Stack 
* stack = new Stack ;
    iniStack(stack) ;
    push(stack , 
4);
    push(stack , 
5) ;
    cout
<<pop(stack) ;
    cout
<<pop(stack) ;
    cin.
get() ;
  
  
return 0 ;    
 }

 
 
void push(Stack *stack , int x) 
 
{
   
if(!full(stack))
      
{
        stack
->a[stack->top++= x ;
                      
      }
 
   
else 
      cout
<<"error full"<<endl ;
 }

 
 
int pop(Stack * stack)
 
{
   
if(empty(stack))  
     
return - 1 ;
   
else
    
return stack->a[--stack->top] ;
       
 }
  
  
  
  
void iniStack(Stack * stack)
  
{
    stack
->top = 0 ;      
  }


  
bool empty(Stack * stack)
  
{
    
return stack->top == 0 ;       
  }

  
  
bool full(Stack * stack)
   
{
     
return stack->top == N ;     
   }

  
  
   
   
 

   
 


2 队列的操作
   队列为空的判断条件,tail == head 。队列采用head插入,TAIL弹出。

   队列为满的条件是,(HEAD + 1) % N = TAIL。
  
  

   代码如下:
    

#include <iostream>
 
using namespace std ;
 
const int N = 10 ;
 
struct Queue
 
{
    
int head ; //头部插入    
    int tail ; //尾部取出    
    int a[N] ;    
 }
 ;
 
 
bool empty(Queue * queue) ;
 
bool full (Queue * queue) ;
 
void enqueue( Queue * queue , int x) ;
 
int  dequeue(Queue * queue) ;
 
void iniQueue(Queue * queue) ;
 
int main()
 
{
   Queue 
* queue = new Queue ;
   iniQueue(queue);
   enqueue(queue , 
4) ;
   enqueue(queue , 
5) ;
   cout
<<dequeue(queue) ;
   cout
<<dequeue(queue) ;
   cin.
get() ;
   
return 0 ;    
 }
 

 
void iniQueue(Queue * queue)
 
{
   queue
->head = 0 ;
   queue
->ta il = 0 ;        
 }


  
void enqueue( Queue * queue , int x)
  
{
       
if(!full(queue))
       
{
        queue
->a[queue->head++]  = x;                
       }

       
else
        cout
<<"full"<<endl ;
  }


  
int dequeue(Queue * queue) 
  
{
    
if(!empty(queue))
      
{
        
return queue->a[queue->tail++] ;             
      }

      
else
      
{
      cout
<<"empty"<<endl;  
       
return -1 ;
      }

  }

  
  
  
bool empty(Queue * queue)
  
{
    
return queue->tail == queue->head ;        
  }

  
   
bool full(Queue * queue)
   
{
    
return (queue->head + 1 ) % N == queue->tail ;      
   }

  





 

posted on 2011-04-10 10:42 kahn 阅读(787) 评论(1)  编辑 收藏 引用 所属分类: 算法相关

Feedback

# re: 队列和栈的基本操作 2011-12-11 07:19 jemmyLiu

博主判断队列满的情况好像不对
bool full(Queue* queue)
{
if (queue->head != 0)
{
return (queue->head)%N == queue->tail;
}

return false;
}
是否是我写错了 请指教  回复  更多评论   



只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理