【问题标题】:Displaying the data of a queue after its deletion删除队列后显示队列的数据
【发布时间】:2021-10-26 17:32:42
【问题描述】:

我正在使用 c 中的 struct 创建一个队列来存储客户。我可以删除客户节点,但我想显示已删除客户的信息,即姓名和条形码编号

typedef struct customer {
char name[50];          // the customer's name
double barcodeNumber;   // the barcode number from the customer's ticket
struct customer *next;  // a pointer to the next customer in the queue after this one
}
Customer;

typedef struct eventQueue {
Customer *head; // points to the customer at the front/head of the queue
Customer *tail; // points to the customer at the end/tail of the queue
} EventQueue;

这是我的删除功能

int removeCustomer(EventQueue *qPtr, Customer *c)
{


if(qPtr == NULL)
return INVALID_INPUT_PARAMETER;

if(c == NULL)
return INVALID_INPUT_PARAMETER;

if(qPtr->head == NULL)
return INVALID_QUEUE_OPERATION;


char *name;
double barcode;

strcpy(c->name,name);
barcodeCopy = c->barcode;


c=qPtr->head;
qPtr->head=qPtr->head->next;
free(c);


// Value to be returned if a function is completed successfully
return SUCCESS;
}

这是我的代码实现

void main()
{
printf("\nAttempting to remove customer from queue..");

// (attempt to) remove / pop a customer from the queue
Customer customerInfo;
 // a variable to receive the customer data removed from the queue
result = removeCustomer(pQueue, &customerInfo); // this calls your implementation of removeCustomer()

// if customer wasn't removed successfully
if (result != SUCCESS)
{
    
    printf("ERROR: Unable to remove customer from queue.\n");
}
else
{
    
    printf("..customer removed successfully!\n");

    
    printf("The customer removed was %s who was barcode number %.0lf.\n", customerInfo.name, customerInfo.barcodeNumber);}

}

【问题讨论】:

  • 为什么在c=qPtr->head; 之后不打印?
  • 代码的实现在一个不同的文件(一个测试文件)中,所有的测试和值显示都应该在那里完成
  • 如果我理解正确,您只能修改测试器文件,不能修改带有 Customer 和 EventQueue 的文件?
  • 不,相反,我只能修改 removeCustomer 文件(即第二个),第一个是我不应该更改的头文件,最后一个是我不更改的测试文件不需要改变。主要代码在第二个

标签: c pointers queue


【解决方案1】:

只需分解 removeCustomer 方法中的操作

  1. 从队列中获取“第一/前”客户

    Customer* first = qPtr->head;

  2. 将其数据复制到您作为参数传递的客户信息结构中

    // using first for clarity but qPtr->head->name also works
    strcpy(c->name, first->name);
    c->barcodeNumber = first->barcodeNumber;

  3. 更新队列 - 移除前面

    qPtr->head = qPtr->head->next;

  4. 删除第一个客户(现已提取)

    free(first);

【讨论】:

  • 我想知道为什么你先释放而不是 c。因为 first 或多或少像一个临时结构,用于在删除后存储客户信息
  • 你必须先删除(实际上是first指向的内容),因为它是你在将curstomer添加到队列时动态分配的内存。 c 指向客户信息变量,在堆栈上分配(因此在超出范围时自动删除)。您可以使用它在调用函数中检索第一个客户的副本。
  • 好的,我明白了。谢谢
猜你喜欢
  • 2018-12-11
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 2021-08-31
  • 2015-10-18
  • 1970-01-01
相关资源
最近更新 更多