您的位置:首页 > 职场人生

百度2016届网页搜索面试题 队列单链表的实现(队列大小有限制)

2015-08-14 14:51 639 查看
今天上午网页搜索部门的编程题

改进版请看:面试题 多线程安全队列的实现(改进版)

#include<iostream>

#define MAX 4

using namespace std;

struct Node

{

int data;

struct Node *next;

};

class MyQueue

{

public:

MyQueue();

bool Get(int *&p);

bool Put(int a);

int GetLength();

void Print();

~MyQueue();

private:

struct Node * rear;

struct Node * front;

int length;

};

MyQueue::MyQueue()

{

struct Node *tmp = new struct Node;

tmp->next = NULL;

rear=front=tmp;

length=0;

}

bool MyQueue::Put(int a)

{

struct Node *tmp;

if(length < MAX)

{

rear->data=a;

struct Node *tmp = new struct Node;

tmp->next=NULL;

rear->next = tmp;

rear = tmp;

length++;

return true;

}

else

return false;

}

bool MyQueue::Get(int *&p)

{

if(rear == front)

{

return false;

}

else

{

struct Node *tmp = front;

*p = tmp->data;

front = front->next;

--length;

delete tmp;

tmp = NULL;

return true;

}

}

MyQueue::~MyQueue()

{

if(rear!=front)

{

while(front !=NULL)

{

struct Node *tmp = front;

front = front->next;

delete tmp;

tmp= NULL;

}

rear = front =NULL;

}

}

int MyQueue::GetLength()

{

return length;

}

void MyQueue::Print()

{

struct Node *p = front;

int count = 0;

while(count++ < length)

{

cout<<p->data<<" ";

p = p->next;

}

cout<<endl;

}

int main()

{

MyQueue q;

q.Put(43);

q.Put(12);

q.Put(34);

q.Put(56);

q.Put(45); //超过队列大小的不放入队列

q.Print();

cout <<"队列大小:"<<q.GetLength() << endl;;

int *elem = new int;

q.Get(elem);

cout<<"删除一个元素"<<endl;

q.Print();

cout<<"队列大小:"<<q.GetLength()<<endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: