您的位置:首页 > 编程语言 > C语言/C++

C++程序设计语言课后习题10章12题

2014-09-30 15:41 337 查看
1.向量实现
#include <iostream>
#include <stdexcept>
using namespace std;

class Char_queue{
private:
char *_queue;
unsigned head,tail;
unsigned const capacity;
static unsigned const default_capacity = 20;
public:
Char_queue(unsigned _capacity = default_capacity);
inline char dequeue();
inline void enqueue(const char& );
inline bool empty() const;
inline bool full() const;
~Char_queue();
};

Char_queue::Char_queue(unsigned _capacity):_queue(new char[_capacity]),
head(0),tail(0),capacity(_capacity){}

Char_queue::~Char_queue()
{
delete[] _queue;
}

inline void Char_queue::enqueue(const char& ch)
{
if(full()){
throw std::overflow_error(std::string("queue"));
} else {
_queue[tail]=ch;
tail = (tail+1)%capacity;
}
}

inline char Char_queue::dequeue()
{
if(empty()){
throw std::underflow_error(std::string("queue"));
} else {
char ch=_queue[head];
head = (head+1)%capacity;
return ch;
}
}

inline bool Char_queue::empty() const
{
return head==tail;
}

inline bool Char_queue::full() const
{
return head==(tail+1)%capacity;
}

int main()
{
Char_queue ch_que;
char ch='a';
for(int i=0;i<17;i++)
ch_que.enqueue((char)(ch+i));
while(!ch_que.empty())
cout<<ch_que.dequeue()<<endl;
//ch_que.dequeue();
cout<<endl;
return 0;
}

2.链表实现

#include <iostream>
#include <stdexcept>
using namespace std;

class Char_queue{
private:
struct Node{
char ch;
struct Node* next;
};
Node* head,*tail;
void destroyQueue();
public:
Char_queue();
inline char dequeue();
inline void enqueue(const char& );
inline bool empty() const;
~Char_queue();
};

Char_queue::Char_queue()
{
head = tail = new Node();
head->next = NULL;
}
void Char_queue::destroyQueue()
{
Node *p = NULL;
Node *q = NULL;
for(p=head;p != tail;){
q = p;
p = p->next;
delete q;
}
delete p;
head = tail = NULL;
}
Char_queue::~Char_queue()
{
destroyQueue();
}

inline void Char_queue::enqueue(const char& ch)
{
Node *p = new Node();
p->ch = ch;
p->next = NULL;
tail->next = p;
tail = p;
}

inline char Char_queue::dequeue()
{
if(!empty()){
char chr;
Node *p=head;
head = head->next;
chr=p->ch;
delete p;
return chr;
} else {
throw std::underflow_error("queue");
}
}

inline bool Char_queue::empty() const
{
return head==tail;
}

int main()
{
Char_queue chq;
for(int i=0;i<20;i++)
chq.enqueue('a'+i);
while(!chq.empty())
cout<<chq.dequeue()<<' ';
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: