码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构(3) -- 队列

时间:2015-04-06 01:03:59      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

1、线性存储

//Queue.h
#ifndef QUEUE_H_
#define QUEUE_H_
#define ElemType int 
#define MAXSIZE 100
typedef struct _Node
{
    ElemType data[MAXSIZE];
    int front;
    int rear;
    
}Node;

class Queue
{
private:
    Node data;
public:
    Queue();
    ~Queue();
    void EnQueue(ElemType e);
    ElemType DeQueue();
    int IsFull();
    int IsEmpty();
};

#endif


//Queue.cpp
#include "Queue.h"
#include <iostream>

Queue::Queue()
{
    data.front = 0;
    data.rear = 0;
}

Queue::~Queue(){}

void Queue::EnQueue(ElemType e)
{
    if (IsFull())
    {
        std::cout << "队列已满" << std::endl;
        return;
    }
    data.rear = (data.rear + 1) % MAXSIZE;
    data.data[data.rear] = e;
}

ElemType Queue::DeQueue()
{
    if (IsEmpty())
    {
        std::cout << "队列已空" << std::endl;
        return 0;
    }
    data.front = (data.front + 1) % MAXSIZE;
    return data.data[data.front];
}

int Queue::IsFull()
{
    if (data.front % MAXSIZE == (data.rear + 1) % MAXSIZE)
        return 1;
    else
        return 0;
}

int Queue::IsEmpty()
{
    if (data.front == data.rear)
        return 1;
    else
        return 0;
}

 

2、链式存储

//PQueue.h
#ifndef PQUEUE_H_
#define PQUEUE_H_
#define ElemType int 
#define MAXSIZE 100

typedef struct _PNode
{
    ElemType data;
    _PNode *next;
    
}PNode;

class PQueue
{
private:
    PNode *front;
    PNode *rear;

public:
    PQueue();
    ~PQueue();
    void EnQueue(ElemType e);
    ElemType DeQueue();
    int IsFull();
    int IsEmpty();
};

#endif


//PQueue.cpp
#include "PQueue.h"
#include <iostream>

PQueue::PQueue()
{
    front = new PNode();
    rear = front;
    front->next = NULL;
}

PQueue::~PQueue()
{
    delete front;
    delete rear;
}

void PQueue::EnQueue(ElemType e)
{
    PNode *s = new PNode();
    s->data = e;
    rear->next = s;
    s->next = NULL;
    rear = s;
}

ElemType PQueue::DeQueue()
{
    if (IsEmpty())
    {
        std::cout << "队列已空" << std::endl;
        return 0;
    }
    PNode *s;
    s = front;
    ElemType t = s->next->data;
    front = front->next;
    delete s;
    return t;
}

int PQueue::IsEmpty()
{
    if (rear == front)
        return 1;
    else
        return 0;
}

 

3、测试用例

#include <iostream>
#include "PQueue.h"
#include <string>
using namespace std;



int main()
{
    PQueue q;
    for (int i = 0; i < 6; i++)
        q.EnQueue(i);
    for (int i = 0; i < 6; i++)
        cout << q.DeQueue();
    system("pause");
    return 0;
}

 

数据结构(3) -- 队列

标签:

原文地址:http://www.cnblogs.com/yongssu/p/4395206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!