//
// main.cpp
// Data Structure TRY1
//
// Created by zr9558 on 6/7/13.
// Copyright (c) 2013 zr9558. All rights reserved.
//
// Data Structure C++, Weiss, P.104 Section 3.7 The Queue ADT
/*
http://www.cplusplus.com/reference/queue/queue/
member functions:
empty Test whether container is empty (public member function)
size Return size (public member function)
front Access next element (public member function)
back Access last element (public member function)
push Insert element (public member function)
pop Delete next element (public member function)
*/
#include<iostream>
using namespace std;
template<typename Comparable>
class Queue
{
public:
Queue():head(NULL),tail(NULL){theSize=0;}
Queue(constQueue &rhs)
{
makeEmpty();
*this=rhs;
}
constQueue &operator =(constQueue &rhs)
{
if(this==&rhs)return *this;
makeEmpty();
for(Node *p=rhs.head; p!=NULL; p=p->next)
Push(p->element);
return *this;
}
~Queue() {makeEmpty();}
bool Empty()const {returntheSize==0;}
int Size()const {returntheSize;}
Comparable Front() {returnhead->element;}
Comparable Back() {returntail->element;}
void Push(const Comparable & x)
{
Node * tt=newNode(x,NULL);
if(head!=NULL) {tail->next=tt;tail=tt;}
elsehead=tail=tt;
++theSize;
}
void Pop( )
{
if(head!=NULL)
{
Node *tt=head->next;
Node *pp=head;
head=tt;
--theSize;
delete pp;
}
}
private:
struct Node
{
Comparable element;
Node * next;
Node(const Comparable &x=Comparable(),Node *p=NULL):element(x),next(p){}
};
void makeEmpty()
{
while(!Empty())Pop();
head=tail=NULL;
}
int theSize;
Node *head;
Node *tail;
};
int main()
{
Queue<int> Q;
for(int i=0; i<10; ++i)
Q.Push(i);
Queue<int> Q2, Q3(Q);
Q2=Q3;
cout<<Q.Size()<<endl;
while( !Q.Empty())
{
cout<<Q.Front()<<" "<<Q.Back()<<endl;
Q.Pop();
}
cout<<Q2.Size()<<endl;
cout<<Q3.Size()<<endl;
cout<<Q.Size()<<endl;
while( !Q2.Empty())
{
cout<<Q2.Front()<<" "<<Q2.Back()<<endl;
Q2.Pop();
}
while( !Q3.Empty())
{
cout<<Q3.Front()<<" "<<Q3.Back()<<endl;
Q3.Pop();
}
return 0;
}
本文详细介绍了使用C++实现队列抽象数据类型(ADT)的方法,包括构造函数、拷贝构造函数、析构函数、空队列判断、大小获取、队首元素访问、队尾元素访问、插入元素、删除队首元素等核心功能,并通过实例展示了如何在程序中运用队列数据结构。
1102

被折叠的 条评论
为什么被折叠?



