Time Limit: 1sec Memory Limit:256MB
Description
请完成以下队列类的实现: enum ErrorCode { success, underflow, overflow }; template <class QueueEntry> struct Node { QueueEntry data; Node<QueueEntry> *next; }; template <class QueueEntry> class MyQueue { public: MyQueue(); // 判断队列是否为空 bool empty() const; // 入队操作 ErrorCode append(const QueueEntry &item); // 出队操作 ErrorCode serve(); // 获取队头元素 ErrorCode retrieve(QueueEntry &item) const; // 获取队列已有元素个数 int size() const; // 清除队列所有元素 void clear(); // 获取队头元素并出队 ErrorCode retrieve_and_serve(QueueEntry &item); private: // 请不要修改数据成员. Node<QueueEntry> *front; // 队头指针 Node<QueueEntry> *rear; // 队尾指针 }; 注意,只需要提交类的声明以及函数实现,不需要提交main函数。
Hint
注意,只需要提交类的声明以及函数实现,不需要提交main函数。 |
宛若智障算size()的时候写了个pot=front->next; 万吨死循环怪不得TLE
emmm之后Node的缺省构造函数也是非常重要的一点
#include<iostream>
using namespace std;
enum ErrorCode
{
success,
underflow,
overflow
};
template <class QueueEntry>
struct Node
{
QueueEntry data;
Node<QueueEntry> *next;
Node(QueueEntry data1=0,Node<QueueEntry> *next1=NULL)
{
data=data1;
next=next1;
}
};
template <class QueueEntry>
class MyQueue
{
public:
MyQueue()
{
front=rear=NULL;
}
// 判断队列是否为空
bool empty() const
{
return front==NULL;
}
// 入队操作
ErrorCode append(const QueueEntry &item)
{
if(front==NULL)
{
rear=front=new Node<QueueEntry>(item);
}
else
{
rear=rear->next=new Node<QueueEntry>(item);
}
return success;
}
// 出队操作
ErrorCode serve()
{
if(empty())return underflow;
Node<QueueEntry> *pot=front;
front=front->next;
delete pot;
return success;
}
// 获取队头元素
ErrorCode retrieve(QueueEntry &item) const
{
if(empty())return underflow;
item=front->data;
return success;
}
// 获取队列已有元素个数
int size() const
{
if(empty())return 0;
Node<QueueEntry> *pot=front;
int num=0;
while(pot!=NULL)
{
num++;
pot=pot->next;
}
return num;
}
// 清除队列所有元素
void clear()
{
while(front!=NULL)
{
Node<QueueEntry> *pot=front;
front=front->next;
delete pot;
}
front=rear=NULL;
}
// 获取队头元素并出队
ErrorCode retrieve_and_serve(QueueEntry &item)
{
if(empty())return underflow;
item=front->data;
Node<QueueEntry> *pot=front;
front=front->next;
delete pot;
return success;
}
private:
// 请不要修改数据成员.
Node<QueueEntry> *front; // 队头指针
Node<QueueEntry> *rear; // 队尾指针
};