您的位置:首页 > 其它

链表实现队列

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

代码:

// 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 = nullptr;

return temp;
}
}

void traverse(Linkedlist L)
{
cout << "current queue:";
Node *x = L.head;
if (x == nullptr)
return;
while (x != L.tail)
{
cout << x->data << " ";
x = x->next;
}
if (L.tail != nullptr)
cout << L.tail->data;

cout << endl;
}

int main()
{
int temp;
Linkedlist L;
L.head = nullptr;
L.tail = nullptr;
Node *x;
int cmd;
while (cin >> cmd)
{
switch (cmd)
{
case 1: //入队
cin >> temp;
x = new Node;
x->data = temp;
enqueue(L, x);
traverse(L);
x = nullptr;
break;
case 2: //出队
cout << dequeue(L) << endl;
traverse(L);
break;
default:
cerr << "error command!" << endl;
break;
}
}

system("pause");
return 0;
}



运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: