队列的概念:
现实生活中,经常可以看到队列的例子,如排队买票,先来的人买了票,先离开,后面来的只有等前面离开后,才能买票离开,队列就是类似排队买票的一种数据结构。
队列的定义:
队列是限定在一端进行插入,另一端进行删除特殊线性表。
允许出队的一端称为队头,允许入队的一端称为队尾。
队列的性质:
先进先出(FIFO),先进来的先出去,跟栈的区别,栈是先进后出。
队列的操作:
入队:在队尾加入
出队:在队头离开
队列的表示:
在C++语言里,一般用链表表示队列,先定义每个结点的结构体,定义两个指针head,tail分别指向
队列的头和尾,入队和出队的操作,通过改变指针来进行。具体代码如下:
#include <iostream>
using namespace std;
struct Node
{
int data; //队列元素,可以是其他类型
Node* next; //指向下一个元素的指针
};
Node* head; //队首指针
Node* tail; //队尾指针
void initQueue(); //初始化队列
void addItem(int x);//入队
int outItem();//出队
int main()
{
initQueue();
addItem(11);
addItem(12);
addItem(13);
cout<<outItem()<<endl;
cout<<outItem()<<endl;
cout<<outItem()<<endl;
cout<<outItem()<<endl;
cout<<outItem()<<endl;
cout<<outItem()<<endl;
cout<<outItem()<<endl;
return 0;
}
void initQueue() //初始化时,首尾指针指向相同的位置
{
Node *temp = new Node;
head =temp;
tail =temp;
tail->next =NULL;
}
void addItem(int x) //入队时,改变尾指针指向
{
Node *temp = new Node;
temp->data =x;
temp->next =NULL;
tail->next =temp;
tail = temp;
}
int outItem() //出队,先判断队列是否为空
{
if (head == tail)
{
cout<<"队列已空"<<endl;
return 0;
}
Node *temp = new Node;
temp = head->next;
int x=temp->data;
head =head->next;
return x;
}
队列相关的题目:
已知队列(13,2,11,34,77,5,7,18,26,15)第一个进入队列的元素是13,则第五个出队列的元素是()
A.5 B.41 C.77 D.13 E.18
网友评论