Data structure and algorithm-6 queue

queue

Only allow inserting at one end and deleting at the other end.
End of line: Insertion is allowed.
Head of line: Deletion
is allowed. Features: First-in, first-out FIFO

Team empty condition: Q.rear == Q.front
team full condition: (Q.rear +1)% MaxSize == Q.front
queue element number: (rear + Maxsize-front)% Maxsize

typedef struct{
    
    
	ElemType data[MaxSize];	//用静态数组存放队列元素 
	int front, rear;		//队头,队尾指针 
}SqQueue;

void InitQueue(SqQueue &Q){
    
    
	Q.rear=Q.front= 0;		//初始时 队头、队尾指针指向0 
}

bool EnQueue(SqQueue &Q, ElemType x){
    
    
	if (队列已满)
		return false;
	 Q.data[Q.rear] = x;	//将x插入队尾
	 Q.rear = Q.rear+1;//队尾指针加一
	 return true;
	  
}

牛逼循环队列
bool EnQueue(SqQueue &Q, ElemType x){
    
    
	if (队列已满)
		return false;
	 Q.data[Q.rear] = x;	//将x插入队尾
	 Q.rear = (Q.rear+1) % MaxSize;//队尾指针加一取余  循环队列 
	 return true;
	  
}

出队
bool DeQueue(SqQueue &Q, ElemType & x){
    
    
	if(Q.rear == Q.front)		//判断队空
		return false;
	x = Q.data[Q.front];
	Q.front = (Q.front+1)% MaxSize;
	return true;
	 
}bool GetHead(SqQueue Q, ElemType & x){
    
    
	if(Q.rear == Q.front)		//判断队空
		return false;
	x = Q.data[Q.front];
	return true;
	 
} 

In the general circular queue, an area needs to be vacated to determine whether the queue is full or empty,
but it is okay.

typedef struct{
    
    
	ElemType data[MaxSize];	//用静态数组存放队列元素 
	int front, rear;		//队头,队尾指针 
	int size;
}SqQueue;

Use size to judge, this can save a space
size == MaxSize, full
size == 0, empty

You can also use tag

typedef struct{
    
    
	ElemType data[MaxSize];	//用静态数组存放队列元素 
	int front, rear;		//队头,队尾指针 
	int tag;
}SqQueue;

When tag = 0, a deletion has been performed recently, and when
tag = 1, an insertion has been performed recently

front == rear&&tag == 1,满
front == rear&&tag == 0,空

Guess you like

Origin blog.csdn.net/fly_ship/article/details/109008636