循环链表C ++

时间:2016-02-24 22:17:55

标签: c++ linked-list queue

我尝试使用循环链表创建队列。我只是采用了我现有的链表实现(已经可以工作)并改变了节点指向的位置,但它似乎并不那么简单。我确定这是我忽视的一件小事。

void enqueue(int q){
    newNode=new node;
    newNode->info = q;
    newNode->link = first;

    if(first->link==first){
        first = last = newNode;
        last->link=first;
    }

    else{
       last->link = newNode;
       last= newNode;
       last->link = first;
    }           
}

int dequeue(){
    int x;
    if(first->link==first){
        cout <<"The Queue is empty" <<endl;
        return 0;
    }
    else{
        dummy=first;
        x=dummy->info;
        first=first->link;
        delete(dummy);
        return(x);
    }
}

1 个答案:

答案 0 :(得分:0)

我把它转换成了一个班级。对于循环列表类,只需要指向最后一个节点的指针,如first = last-&gt; next。由于没有使用虚节点,因此空列表通常由last == NULL;

表示
#include<iostream>

class circq
{
    typedef struct node_
    {
        struct node_ *next;
        int info;
    }node;

    node *last;                         // ptr to last node of list

public:

    circq()                             // constructor
    {
        last = NULL;                    // reset last
    }

    bool isempty()
    {
        return last == NULL;
    }

    void enqueue(int q)
    {
        node *newNode=new node;         // new node
        newNode->info = q;
        if(last == NULL){               // if empty list
            last = newNode;             //  create single node list
            newNode->next = newNode;
            return;
        }                               // else
        newNode->next = last->next;     //  append node to end list
        last->next = newNode;
        last = newNode;
    }

    int dequeue()
    {
        if(last == NULL){               // check for empty list
            return 0;
        }
        node *first = last->next;       // set ptr to first node
        int x = first->info;            // set return value
        if(last->next == last)          // if single node
            last = NULL;                //  set list to empty
        else                            // else
            last->next = first->next;   //  advance first to next node
        delete first;                   // delete node
        return x;
    }

    ~circq()                            // destructor
    {
        while(!isempty())
            dequeue();
    }
};

int main()                              // test circq
{
circq cq;
    cq.enqueue(0);
    cq.enqueue(1);
    cq.enqueue(2);
    cq.enqueue(3);
    while(!cq.isempty())
        std::cout << cq.dequeue() << std::endl;
    return 0;
}