这里利用C++实现队列:
队列使用类来实现,类中有数据和指针两项,数据为队列中每项的数据,指针为队列的当前元素指向下一个元素;
class Queue23
{
private:
int data;
Queue23* next;
public:
Queue23();
~Queue23() { cout << "destructor is called!" << endl; }
Queue23* Enqueue(int data,Queue23* rear); //入队
Queue23* Dequeue(Queue23* head,Queue23* rear); //出队
Queue23* GetHead(Queue23* head) { return head->next; }
Queue23* GetThis() { return this; }
int GetData() { return data; }
};
Queue23::Queue23()
{
data = 0;
next = NULL;
}
//数据入队
Queue23* Queue23::Enqueue(int data, Queue23* rear)
{
this->data = data;
if (rear->next == NULL)
{
rear->next = this;
rear = this;
rear->next = NULL;
//cout << this << "\t" << rear << endl;
}
return rear;
}
//数据出队
Queue23* Queue23::Dequeue(Queue23* head, Queue23* rear)
{
Queue23* p;
if (head->next == NULL)
{
cout << "queue is empty!" << endl;
return NULL;
}
p = head->next;
cout << p->data << endl;
head->next = p->next;
if (p != NULL)
{
delete p;
}
return head;
}
这里需要注意的是,由于上一个元素需要利用指针指向下一个元素,所以对象的建立需要用到new来分配堆上内存(同时要注意内存的释放);
下面可以验证一下:
int main()
{
Queue23* temp = new Queue23;
Queue23* head ;
Queue23* rear;
//cout << temp->GetData() << endl;
head = rear = temp;
//cout <<"temp=" << temp << endl;
//cout << head << " \t" << rear << endl;
int data[5] = { 12,25,56,57,89 };
//Queue23 ad;
for (int i = 0; i < 5; i++)
{
Queue23* ad = new Queue23;
rear = ad->Enqueue(data[i], rear);
// cout <<head << " \t" << rear << endl;
//cout << ad->GetThis() << endl;
//cout << ad->GetData();
}
//cout << head<<" \t" << rear << endl;
while (head->GetHead(head))
{
head = head->Dequeue(head, rear);
}
return 0;
}
结果如下: