链表实现队列

本文介绍如何利用链表实现队列数据结构,通过维护头结点和尾结点,确保在入队和出队操作中保持高效,避免全链表遍历。
摘要由CSDN通过智能技术生成

思路:队列涉及到两端的操作,所以使用头结点和尾结点两个指针,避免在入队操作时遍历整个链表。

代码:

// linkedlistqueue.cpp : 定义控制台应用程序的入口点。
// 链表实现队列

#include "stdafx.h"
#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::cerr;

//点结构
typedef struct Node {
	int data;
	Node *prev; //指向前驱结点
	Node *next; //指向后继结点
};

//链表结构
typedef struct Linkedlist {
	Node *head; //头结点
	Node *tail; //尾结点
};

//插入结点
void enqueue(Linkedlist &L, Node *x)
{
	x->prev = L.tail;
	if (L.tail != nullptr)
		L.tail->next = x;
	L.tail = x;
	x->next = nullptr;

	if (L.head == nullptr) //连接头尾结点
		L.head = L.tail;
}

//删除头结点
int dequeue(Linkedlist &L)
{
	if (L.head == nullptr)
	{
		cerr << "queue underflow!" << endl;
		return -1;
	}
	else
	{
		int temp = L.head->data;
		if (L.head->next != nullptr)
			L.head = L.head->next;
		else
			L.head 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值