Basic Usage of Queue

   We can know some things from the book.


#include <iostream>
#include <stdlib.h>
using namespace std;
typedef int QueueElementType;

// Generally, the operation is to package  the head pointer of the queue and the tail pointer of the queue
//  in one structure 
// Defintion of queue structure
typedef struct Node{
	QueueElementType data;    // data region
	struct Node* next;  // pointer domain
}LinkQueueNode;

typedef struct{
	LinkQueueNode * front;  //
	LinkQueueNode * rear;  
}LinkQueue;

// we need to have mastered the most basic operation such as initialize、incoming queue、 out of queue and so on

// Initialize the queue

void InitQueue(LinkQueue * Q)
{   // Initialize the queue Q  to an empty queue
    Q->front = (LinkQueueNode * )malloc(sizeof(LinkQueueNode));
    if(Q->front!=NULL)
    {
    	Q->rear = Q->front;
    	Q->front->next = NULL;
	}
	else {
		// overflow
	}
}

// incoming queue
void EnterQueue(LinkQueue * Q,QueueElementType x)
{  // Insert the element x into the queue Q
   LinkQueueNode * NewNode;
   NewNode =(LinkQueueNode * )malloc(sizeof(LinkQueueNode));
   if(NewNode!=NULL)
   {
   	  NewNode->data = x;
   	  NewNode->next = NULL;
   	  Q->rear->next = NewNode;
   	  Q->rear = NewNode;
   }
   else{
   	    cout << "failure"<<endl;
   }
}

// out of queue ,similar to deleting an element from the queue
void DeleteQueue(LinkQueue * Q,QueueElementType * x)
{  // Out of  an element from the queue Q and reserve the element in the definition constant x.
   LinkQueueNode  * p;
   if(Q->front == Q->rear)
   {
   }
   p = Q->front->next;   // the head element of the queue
   Q->front->next = p->next;  // similar to deleting the head element of the queue
   if(Q->rear == p)   // if the queue has only one element,p becomes an empty queue after it leaves the queue
   { 
   	Q->rear = Q->front;
   }
   *x = p->data;  // reserve the "p->data" in x
   free(p);  // release memory space 
}




int main()
{
  LinkQueue Q;
  InitQueue(&Q);
  cout << " input a number is 2"<<endl; 
  cout << " execute Enter..." <<endl;
  EnterQueue(&Q,2);
  
  int x;
  cout << " execute Delete..." <<endl;
  DeleteQueue(&Q,&x);
  
  cout << " Save the deleted elements to x,and  x's value: " << x <<endl;
  
  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值