4

我无法理解这一行:

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
4

3 回答 3

5

rear指向最后一个元素。想要的是放置temp在 current 之后rear,然后移动rear到指向新放置的最后一个元素。所以,如果我们想要加入4队列(1, 2, 3),我们​​想要:

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

您的解决方案让tempcut 在 current 前面rear,然后移动rear到 cut 位置。它甚至没有正确切割,因为 . 之前的项目rear仍然指向原始rear. rear不再指向最后一项,因此您的队列将处于不一致的状态。

1 -> 2 -> 3
|      4 -^
|      |
front  rear
于 2013-07-31T03:32:06.463 回答
2

该代码对我来说很有意义

if(front == 0)
  front = temp;

这意味着队列是空的。添加您的元素,并使前指针指向您唯一的元素。你已经明白这一点了。

else
   rear->next = temp;

否则,队列中已经存在元素。所以去最后一个元素,后面,把新元素放在最后面。这是现在的新后方。旧后方的下一个指针现在指向您的新后方。

rear = temp;

做新的后方官员!

于 2013-07-31T03:38:40.387 回答
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;

}
于 2015-10-07T15:50:21.940 回答