链队列.cpp [数据结构实现 之 队列]
第一次把代码贴到博客首页,有点小激动,咳咳,恩,啥也不说了,直接贴代码,这是哥这几天写的"最艰难的"代码了,
还是那句话,一家之言,欢迎拍砖.....::>_<::
代码实现:
#include <iostream>#include <malloc.h>#include <iomanip>using namespace std;#define OVERFLOW -2enum status {success,underflow,overflow,range_error};class Node{public: int data; Node *next;};class LinkQueue{private: Node *top; Node *rear;public: LinkQueue(); ~LinkQueue(); status clear(void); status push(const int &item); status pop(void); status front(int &item) const; status traverse(void) const; bool empty(void) const; int length(void) const;};LinkQueue::LinkQueue(){ top = rear = new Node; if (!top) exit(OVERFLOW); top -> next = NULL;}LinkQueue::~LinkQueue(){ while (top) { rear = top -> next; free(top); top = rear; }}bool LinkQueue::empty() const{ return (top == rear);}int LinkQueue::length(void) const{ Node *searchp = top -> next; int i; for (i = 0; searchp; i++) searchp = searchp -> next; return i;}status LinkQueue::clear(void){ Node *searchp,*followp; rear = top; searchp = top -> next; top -> next = NULL; while (searchp) { followp = searchp; searchp = searchp -> next; free(followp); } return success;}status LinkQueue::push(const int &item){ Node *newnode = new Node; if (!newnode) exit(OVERFLOW); newnode -> data = item; newnode -> next = NULL; rear -> next = newnode; rear = rear -> next; return success;}status LinkQueue::pop(void){ if (empty()) return underflow; Node *newnode = top -> next; top -> next = newnode -> next; if (rear == newnode) rear = top; free(newnode); return success;}status LinkQueue::front(int &item) const{ if (empty()) return underflow; item = top -> next -> data; return success;}status LinkQueue::traverse(void) const{ if (empty()) { cout << "Queue is empty!" << endl; return underflow; } cout << "All datas:"; Node *searchp = top -> next; while (searchp) { cout << ' ' << searchp -> data; searchp = searchp -> next; } cout << endl; return success;}int main(){ LinkQueue q; cout << "push:" << endl; for (int i = 0; i < 20; i++) q.push((i+1) * 11); q.traverse(); cout << "===================\n" << endl; cout << "push again!" << endl; q.push(89); q.traverse(); cout << "===================\n" << endl; cout << "front:" << endl; int item; q.front(item); cout << item << endl; cout << "===================\n" << endl; cout << "pop_front 2s:" << endl; q.pop(); q.pop(); q.traverse(); cout << "front:" << endl; q.front(item); cout << item << endl; cout << "===================\n" << endl; cout << "Queue's size is: " << q.length() << '\n' << endl; cout << "Clear:" << endl; q.clear(); q.traverse(); cout << "Queue's size is: " << q.length() << '\n' << endl;}