这个排队功能如何运作?

时间:2013-07-31 03:28:18

标签: c++ algorithm data-structures queue

我无法理解这一行:

rear->next = temp;

在此队列函数中:

 void Queue::enqueue(int data) {

    Node *temp = new Node();    // make a temporary node
    temp->info = data;          // assign passed in data to it
    temp->next = 0;             // make it point to null

    if(front == 0)              // if there is no front node
        front = temp;           // make this a front node

    else                        // else, if there is already a front node
        rear->next = temp;      // make this rear's next pointer???? why?

    rear = temp;                // in any case make this a rear node

}

这样做会不会更有意义吗?

    else                    // else, if there is already a front node
        temp->next = rear;  // make temp point to REAR; not other way around

    rear = temp;                // make temp a new rear node

3 个答案:

答案 0 :(得分:5)

rear指向最后一个元素。需要的是在当前temp之后放置rear,然后移动rear以指向新放置的最后一个元素。因此,如果我们想要将4排入队列(1, 2, 3),我们希望:

1 -> 2 -> 3 -> 4
|              |
front          rear

您的解决方案允许temp在当前rear前切割,然后将rear移至切割位置。它甚至没有正确切割,因为rear之前的项仍然指向原始rearrear不再指向最后一项,因此您的队列将处于不一致状态。

1 -> 2 -> 3
|      4 -^
|      |
front  rear

答案 1 :(得分:2)

该代码对我有意义

if(front == 0)
  front = temp;

这意味着队列为空。添加元素,并使前指针指向唯一的元素。你已经理解了这一点。

else
   rear->next = temp;

否则,队列中已存在元素。所以转到最后一个元素,后面,并将新元素放在最后面。这是现在的新后方。旧后方的下一个指针现在指向你的新后方。

rear = temp;

成为新的后方官员!

答案 2 :(得分:0)

这个简单的队列示例将帮助您了解入队的工作情况

#include<iostream>

#include<cstdlib>

using namespace std;

struct node{

int info;

struct node *next;

};

class Queue{

private:

node *rear;

node *front;

public:

Queue();

void enqueue();

void dequeue();

void display();

};

Queue::Queue(){

rear = NULL;

front = NULL;

}

void Queue::enqueue(){

int data;

node *temp = new node;

cout<<"Enter the data to enqueue: ";

cin>>data;

temp->info = data;

temp->next = NULL;

if(front == NULL){

    front = temp;

}else{

    rear->next = temp;

}

rear = temp;

}

void Queue::dequeue(){

node *temp = new node;

if(front == NULL){

    cout<<"\nQueue is Emtpty\n";

}else{

    temp = front;

    front = front->next;

    cout<<"The data Dequeued is "<<temp->info;

    delete temp;

}

}

void Queue::display(){

node *p = new node;

p = front;

if(front == NULL){

    cout<<"\nNothing to Display\n";

}else{

    while(p!=NULL){

        cout<<endl<<p->info;

        p = p->next;

    }

}

}

int main(){

Queue queue;

int choice;

while(true){

    cout<<"\n1.Enqueue\n2. Dequeue\n3. Display\n4.Quit";

    cout<<"\nEnter your choice: ";

    cin>>choice;

    switch(choice){

        case 1:

            queue.enqueue();

            break;

        case 2:

            queue.dequeue();

            break;

        case 3:

            queue.display();

            break;

        case 4:

            exit(0);

            break;

        default:

            cout<<"\nInvalid Input. Try again! \n";

            break;

    }

}

return 0;

}