# include <iostream>
using namespace std;
typedef struct node
{
int data;
struct node *pNext;
}NODE, *PNODE;
class Queue
{
private:
PNODE pHead, pTail; //pHead指向无用的头结点 pHead->pNext才是指向队首元素, pTail指向队尾元素
public:
Queue(/* args */)
{
this->pHead = this->pTail = new NODE;
this->pHead->pNext = NULL;
}
void lnQueue(int val)
{
PNODE pNew = new NODE;
pNew->data = val;
pNew->pNext = NULL;
pTail->pNext = pNew; //将pNew挂到队列尾部
pTail = pNew; //注意是尾指针上移
return;
}
bool Empty()
{
if (pHead == pTail)
{
return true;
}
else
{
return false;
}
}
int OutQueue()
{
int val;
if (Empty())
{
cout <<"链表为空!!!" <<endl;
}
else
{
PNODE p = pHead->pNext;//pHead不是要删除的队首元素,pHead->pNext所指向的元素才是要删除的元素,
pHead->pNext = p->pNext;//p = p->pNext是错,不能改变pHead->pNext的值
val = p->data;
delete p;
if (NULL == pHead->pNext)//队列为空的情况,需要操作一手pTail,让它指向第一个没用的节点
{
pTail = pHead;
}
return val;
}
}
void Travers(void) const
{
PNODE p = pHead->pNext;
while (NULL != p)
{
cout << p->data << " ";
p = p->pNext;
}
cout << endl;
}
void Clear()
{
while (! Empty())
{
OutQueue();
}
}
~Queue()
{
this->Clear();
delete pHead;
}
};
int main(void)
{
Queue Q;
Q.lnQueue(5);
Q.lnQueue(6);
Q.lnQueue(7);
Q.Travers();
Q.OutQueue();
Q.Travers();
return 0;
}
数据结构--链式队列
最新推荐文章于 2024-07-13 16:00:03 发布