1.什么是队列?
2.队列的抽象数据类型描述
3.队列之顺序表的C语言实现
#include <stdio.h>
#include <stdlib.h> #define MaxSize 5
#define ElementType int
#define ERROR -1 typedef struct QNode * Queue;
struct QNode{ ElementType Data[ MaxSize] ; int rear; int front;
} ;
Queue PtrQ;
Queue MakeEmpty ( )
{ Queue PtrQ; PtrQ= ( Queue) malloc ( sizeof ( struct QNode) ) ; PtrQ-> rear= 0 ; PtrQ-> front= 0 ; return PtrQ;
}
void AddQ ( ElementType item, Queue PtrQ)
{ if ( ( PtrQ-> rear+ 1 ) % MaxSize== PtrQ-> front) { printf ( "队列满\n" ) ; return ; } PtrQ-> rear= ( PtrQ-> rear+ 1 ) % MaxSize; PtrQ-> Data[ PtrQ-> rear] = item;
}
ElementType DeleteQ ( Queue PtrQ)
{ if ( PtrQ-> rear== PtrQ-> front) { printf ( "队列为空,无法删除\n" ) ; return ERROR; } PtrQ-> front= PtrQ-> front+ 1 ; return PtrQ-> Data[ PtrQ-> front] ;
}
int Length ( Queue PtrQ)
{ return PtrQ-> rear- PtrQ-> front;
} int main ( )
{ int i, LengthQ; PtrQ= MakeEmpty ( ) ; AddQ ( 24 , PtrQ) ; AddQ ( 34 , PtrQ) ; AddQ ( 45 , PtrQ) ; AddQ ( 76 , PtrQ) ; AddQ ( 89 , PtrQ) ; LengthQ= Length ( PtrQ) ; printf ( "队列长:%d\n" , LengthQ) ; for ( i= PtrQ-> front+ 1 ; i< PtrQ-> rear+ 1 ; i++ ) { printf ( "%d " , PtrQ-> Data[ i] ) ; } printf ( "\n" ) ; printf ( "删除:%d\n" , DeleteQ ( PtrQ) ) ; LengthQ= Length ( PtrQ) ; printf ( "队列长:%d\n" , LengthQ) ; for ( i= PtrQ-> front+ 1 ; i< PtrQ-> rear+ 1 ; i++ ) { printf ( "%d " , PtrQ-> Data[ i] ) ; } printf ( "\n" ) ; return 0 ;
}
4.队列之链式表的C语言实现
#include <stdio.h>
#include <stdlib.h> #define ElementType int
#define ERROR -1 typedef struct QNode * Queue;
struct QNode{ ElementType Data; Queue Next;
} ;
Queue MakeEmpty ( )
{ Queue PtrQ; PtrQ = ( Queue) malloc ( sizeof ( struct QNode) ) ; PtrQ-> Next= NULL ; return PtrQ;
}
Queue AddQ ( ElementType item, Queue Rear)
{ Queue PtrQ; PtrQ= ( Queue) malloc ( sizeof ( struct QNode) ) ; PtrQ-> Data= item; PtrQ-> Next= NULL ; Rear-> Next= PtrQ; Rear= PtrQ; return Rear;
}
Queue DeleteQ ( Queue Front, Queue Rear)
{ Queue PtrQ; if ( Front-> Next== NULL ) { printf ( "队列为空\n" ) ; return Rear; } PtrQ= Front-> Next; printf ( "删除元素:%d\n" , PtrQ-> Data) ; Front-> Next= PtrQ-> Next; if ( PtrQ== Rear) { Rear= Front; } free ( PtrQ) ; return Rear;
}
int Length ( Queue Front, Queue Rear)
{ int i= 0 ; while ( Front!= Rear) { i++ ; Front= Front-> Next; } return i;
} int main ( )
{ int i, length; Queue Rear, Front; Front= Rear= MakeEmpty ( ) ; Rear= AddQ ( 23 , Rear) ; Rear= AddQ ( 51 , Rear) ; Rear= AddQ ( 78 , Rear) ; length= Length ( Front, Rear) ; printf ( "队列长:%d\n" , length) ; Queue PtrQ1= Front-> Next; for ( i= 0 ; i< length; i++ ) { printf ( "%d " , PtrQ1-> Data) ; PtrQ1= PtrQ1-> Next; } printf ( "\n" ) ; Rear= DeleteQ ( Front, Rear) ; length= Length ( Front, Rear) ; printf ( "队列长:%d\n" , length) ; Queue PtrQ2= Front-> Next; for ( i= 0 ; i< length; i++ ) { printf ( "%d " , PtrQ2-> Data) ; PtrQ2= PtrQ2-> Next; } printf ( "\n" ) ; return 0 ;
}