单链表实现队列的基本操作(入队,出队)

单链表实现队列的基本操作(包括初始化队列,入队,出队)


  1. 构造队列结构体
struct node {
    int data;
    node *next;
};

struct queue {
    node *head, *tail;
};
  1. 队列初始化
queue* create(queue *q) {
    q->head = new node;
    q->head->next = NULL;
    q->tail = q->head;
    return q;
}
  1. 插入队列(尾插)
//插入时间复杂度o(1)
void push(queue *q, int value) {
	//尾插 
	node *ins = new node;
	ins->data = value;
	ins->next = q->tail->next;
	q->tail->next = ins;
	//移动尾指针 
	q->tail = ins;
}
  1. 出队,(头出)
//出队时间复杂度o(1)
void pop(queue *q) {
	//头出 
	if(q->head == q->tail) {
		cout<<"it is an empty queue!"<<endl;
		return;
	} else {
		node *temp = q->head->next;
		q->head->next = q->head->next->next;
		delete temp;
	}
}
  1. 遍历队列
void display (queue *q) {
	if (q->head == q->tail) {
		cout<<"it is an empty queue!"<<endl;
		return;
	} else {
		node *temp = q->head;
		while (temp->next) {
			cout<<temp->next->data<<endl;
			temp = temp->next;
		}
	}
}

主函数

int main() {
	//不是queue *q; 
	queue *q= new queue;
	q = create(q);
	
	//测试构建队列和入队
	int n;
	cin>>n;
	while (n-->0) {
		int value;
		cin>>value;
		push(q,value);
	}
	display(q);
	
	//出队
	pop(q);
	display(q);
	return 0;
} 

版权声明:本文为qq_32070219原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。