[Data structure] Implementation of C language queue

Queue definition

Queue: It is a special linear table that only allows inserting data at one end and deleting data at the other end. The queue has first-in first-out.

Basic operation of the queue

Enqueue: The end of the insert operation is called the end of the queue
Dequeue: The end of the delete operation is called the head of the team

The queue can also be realized in the structure of sequential table (array) and linked list, because the queue supportsEnd insertion and header deletion, So the linked list is more suitable to implement the queue
Insert picture description here

Implementation of the queue

The singly linked list with head and tail pointers in C language implements the queue:

Definition of queue

typedef int Data;
typedef struct queuenode{
    
    
	Data data;
	struct queue* _next;
}queuenode;

typedef struct queue{
    
    
	queuenode* _start;
	queuenode* _end;
}queue;

Initialization of the queue

void init(queue* qe){
    
    
	qe->_end = qe->_start = NULL;
}

Queue expansion

queuenode* createqe(Data data){
    
    
	queuenode* node = (queuenode*)malloc(sizeof(queuenode));
	node->data = data;
	node->_next = NULL;
}

Enqueue and Dequeue

//入队(尾插)
void push(queue* qe, Data data){
    
    
	queuenode* newqueue=createqe(data);
	if (qe->_end == qe->_start == NULL){
    
    
		qe->_end = qe->_start = newqueue;
	}
	else{
    
    
		qe->_end->_next = newqueue;
		qe->_end = newqueue;
	}
}

//出队(头删)
void pop(queue* qe){
    
    
	if (qe->_end == NULL){
    
    
		return;
	}
	queuenode* next = qe->_start->_next;
	free(qe->_start);
	qe->_start = next;
	//删除之后是否为空表
	if (qe->_end == NULL){
    
    
		qe->_end = NULL;
		//避免end变为野指针
	}
}

Get the head or tail of the team

//获取队头元素
int top(queue* qe){
    
    
	return qe->_start->data;
}

int last(queue* qe){
    
    
	return qe->_end->data;
}

Get the number of elements

/获取数量
int size(queue* qe){
    
    
	if (qe->_end == NULL){
    
    
		return 0;
	}
	int i = 0;
	queuenode* cur = qe->_start;
	while (cur){
    
    
		i++;
		cur = cur->_next;
	}
	return i;
}

Destroy the queue

void destory(queue* qe)
{
    
    
	assert(qe);
	queuenode* cur = qe->_start;
	while (cur)
	{
    
    
		queuenode* next = cur->_next;
		free(cur);
		cur = next;
	}
	qe->_start = qe->_end = NULL;
}

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/114581366