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

本文详细介绍使用单链表实现队列数据结构的方法,包括队列的初始化、元素的入队与出队操作,以及队列的遍历。通过具体代码示例,展示了如何在C++中构建和操作队列,特别强调了尾插和头出的操作,以及其时间复杂度为O(1)的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  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;
} 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值