1 #include <iostream> 2 #include <stdlib.h> 3 4 using namespace std; 5 6 typedef struct QNode 7 { 8 int data; 9 struct QNode *next; 10 }QNode; //队结点 11 typedef struct 12 { 13 QNode *front; 14 QNode *rear; 15 }LiQueue;//链队类型 16 17 void InitQueue(LiQueue *&Q) 18 { 19 Q=(LiQueue*)malloc(sizeof(LiQueue)); 20 Q->front=Q->rear=NULL; 21 } 22 23 int IsEmpty(LiQueue *Q) 24 { 25 if(Q->front==NULL||Q->rear==NULL) 26 return 1; 27 else 28 return 0; 29 } 30 31 void EnQueue(LiQueue *Q,int e) 32 { 33 QNode *p; 34 p=(QNode*)malloc(sizeof(QNode)); 35 p->data=e; 36 p->next=NULL; 37 38 if(Q->rear==NULL) 39 Q->front=Q->rear=p; 40 else 41 { 42 Q->rear->next=p; 43 Q->rear=p; 44 } 45 } 46 47 int DeQueue(LiQueue *Q,int &e) 48 { 49 QNode *p; 50 if(Q->rear==NULL) 51 return 0; 52 else 53 p=Q->front; 54 55 if(Q->front==Q->rear) 56 Q->front=Q->rear=NULL; 57 else 58 Q->front=Q->front->next; 59 e=p->data; 60 free(p); 61 return 1; 62 } 63 64 int Print(LiQueue *Q) 65 { 66 if(Q->front==NULL||Q->rear==NULL) 67 { 68 cout<<"\n队空!\n"; 69 return 0; 70 } 71 72 QNode *p; 73 p=Q->front; 74 cout<<"队中元素依次为:\n"; 75 while(p!=Q->rear) 76 { 77 cout<<" "<<p->data<<" "; 78 p=p->next; 79 } 80 cout<<" "<<p->data<<" "; 81 return 1; 82 } 83 84 int main() 85 { 86 int i,e; 87 LiQueue *Q; 88 InitQueue(Q); 89 for(i=0;i<10;++i) 90 EnQueue(Q,i); 91 if(IsEmpty(Q)==1) 92 cout<<"\n队空!\n"; 93 else 94 cout<<"\n队非空!\n"; 95 Print(Q); 96 cout<<"\n--------------------------------\n"; 97 cout<<"依次出队3个元素为:\n"; 98 for(i=0;i<3;++i) 99 { 100 DeQueue(Q,e); 101 cout<<" "<<e<<" "; 102 } 103 if(IsEmpty(Q)==1) 104 cout<<"\n队空!\n"; 105 else 106 cout<<"\n队非空!\n"; 107 Print(Q); 108 cout<<"\n--------------------------------\n"; 109 110 return 0; 111 }
时间: 2024-10-27 12:37:06