【发布时间】:2019-01-20 21:16:00
【问题描述】:
我正在做一个项目,该项目需要我模拟一个客户列表,我可以从一行的前面和后面添加和删除这些客户。为此,我选择使用双向链表数据结构,并创建了两个类 Client 和 ClientLine 来完成它。我的两个类的标题如下所示。
class Client
{
public:
//Default constructor.
//This constructor automatically fills the QueryTime private member
//with a random value upon creation.
Client();
//***** setQueryTime *****
//A function to set the QueryTime private member to a specific value.
void setQueryTime(float SetTime);
//***** getQueryTime *****
//A function to get the private member, QueryTime.
float getQueryTime();
private:
//A variable to hold the time it will take the secretary to answer
//the question.
float QueryTime;
}; //class Client
class ClientLine
{
public:
//A node to go into the list of clients.
typedef struct{
struct clientNode *next; //Points to the next node in the list
struct clientNode *prev; //Points to the previous node in the list
Client currentClient; //The client in the current spot in line.
int clientType; //Tells whether the client is in person or on the phone.
} clientNode;
//Default constructor
//Creates an empty doubly-linked list to represent a
//line of clients (phone and in person).
ClientLine();
//***** isLineEmpty *****
//Boolean function to tell if there is nobody in line.
//The line is empty if listHeader->front == listHeader->rear == NULL.
bool isLineEmpty();
//***** addClientRear *****
//Adds a new client to the rear of the line.
void addClientRear(Client newClient, int clientType);
//***** addClientFront *****
//Adds a new client to the front of the line.
void addClientFront(Client newClient, int clientType);
//***** removeClientRear *****
//Deletes the node at the rear of the list and returns the client from it.
Client removeClientRear();
//***** removeClientFront *****
//Deletes the node at the front of the list and returns the client from it.
Client removeClientFront();
private:
clientNode *front; //Pointer to the front of the list
clientNode *rear; //Pointer to the rear of the list
int listLength; //A variable to hold the length of the list.
}; //class ClientLine
在我的 addClientRear 成员函数中,我尝试使用以下代码将新节点中的指针分配为指向列表中的前一个节点:
//***** addClientRear *****
//Adds a new client to the rear of the line.
void ClientLine::addClientRear(Client newClient, int clientType){
//Make a new node to contain the client.
clientNode *newNode = new clientNode;
newNode->currentClient = newClient;
newNode->clientType = clientType;
//Set the pointers in the new node and list as needed.
if(isLineEmpty()){
front = newNode;
rear = newNode;
newNode->next = NULL;
newNode->prev = NULL;
}
else{
newNode->prev = rear;
newNode->next = NULL;
}
listLength += 1; //increase the length of the list by one.
} //addClientRear()
但是,我在 newNode->prev = rear 语句中收到错误消息:
“ClientLine::clientNode *”类型的值不能分配给“clientNode *”类型的实体
我不确定为什么会出现此错误,因为我正在尝试将指针值分配给另一个指针。任何建议将不胜感激。
【问题讨论】:
-
除了立即提出的问题的答案之外,下面显示的插入逻辑略有损坏。
if语句的“else”部分忘记更新rear指针。
标签: c++ pointers linked-list doubly-linked-list