《面试准备》C++数组、链表实现队列

1、数组实现队列(加了模板)

#include 
using namespace std;
#define MAX 100
//数组实现队列:模板类
template
class MyList
{
public:
    T * buf;
    T front;
    T rear;
public:
    MyList();
    ~MyList(){
        delete [] buf;
        buf = NULL;
        cout<<"delete MyList"<
MyList::MyList(){
    buf = new T[MAX];
    front = 0;
    rear = 0;
}

template
bool MyList::isempty(){
    if(front==rear)
        return true;
    return false;
}

template
bool MyList::isfull(){
    if((rear+1)%MAX==front)
        return true;
    return false;
}

template
void MyList::push_back(T a){
    if(isfull()){
        return;
    }
    buf[rear] = a;
    rear = (rear+1)%MAX;
}

template
T MyList::pop(){
    if(isempty()){
        return -1;
    }
    T pop_num = buf[front];
    front = (front+1)%MAX;
    return pop_num;
}

template
void MyList::ergodic(){
    if(isempty()){
        return;
    }
    if(rear>front){
        for(int i=front;i<=rear-1;i++){
            cout<<"ergodic : "< *mylist =new MyList();
    mylist->push_back(5);
    mylist->push_back(4);
    mylist->push_back(3);
    mylist->ergodic();
    cout<<"front is : "<pop()<pop()<

2、链表实现队列

#include 
#include 
using namespace std;

//单向链表节点
struct ListNode{
    int value;
    struct ListNode *Next;
};

class MyQueue
{
public:                           //成员变量位置
    ListNode *Head;
public:                           //成员函数位置
    MyQueue(){
        Head = new ListNode;      //创建对象的时候调用
    }
    ~MyQueue(){                   //析构函数一般用于释放内存
        delete Head;
        Head = NULL;
    }
    bool isempty();
    void pushback(int n);
    void pop();
    void ergodic();
};

bool MyQueue::isempty(){
    ListNode *P = Head;
    if(P==NULL||P->Next==NULL)
        return true;
    return false;
}

void MyQueue::pushback(int n){
    ListNode *P = Head;
    while(P->Next!=NULL){
        P = P->Next;
    }
    ListNode *tmp = new ListNode;
    tmp->value = n;
    tmp->Next =NULL;
    P->Next = tmp;
    P = tmp;
}

//只有pop不一样,队列是删除第一个节点,栈是删除最后一个节点
void MyQueue::pop(){
    if(isempty())
        return;
    ListNode *P = Head;
    P->Next = P->Next->Next;
}

void MyQueue::ergodic(){
    if(isempty())
        return;
    ListNode *P = Head;
    while(P->Next!=NULL){
        P = P->Next;
        cout<value<pushback(2);
    mystack->pushback(3);
    mystack->pushback(4);
    mystack->pop();
    mystack->ergodic();
    delete mystack;
    mystack = NULL;
    return 0;
}

 

你可能感兴趣的:(笔试)