【问题标题】:Queue Won't extract队列不会提取
【发布时间】:2014-06-06 20:20:36
【问题描述】:

我有这个 C 代码。我制作了一个模拟队列的结构(在后面插入并从前面提取)。插入似乎可以工作,但是当我想用这段代码删除一个节点时,什么也没有发生。

nodo* dequeue(nodo* head) {
    if(head==NULL) {
        return NULL; //nothing to extract
    }
    else {
        nodo* temp=malloc(sizeof(nodo *));
        temp=head;
        head=head->next;
        return temp;
    }
}

这是结构:

typedef struct coda{
 int x;
 char *y;
 char *t;
 int z;
 struct coda *next;
}nodo;

这里是主要的

#include "list.h"

int main(void){
    nodo * testa;
    char* hi="hi";
    char* bye="bye";

    testa=enqueue(15,hi,bye,1,NULL);
    enqueue(16,hi,bye,1,testa);
    enqueue(17,hi,bye,1,testa);
    enqueue(18,hi,bye,1,testa);
    printList(testa);
    nodo *newHead = dequeue(&testa);
    printList(testa);
}

以及其余的代码

nodo* enqueue(int codArt,char *descrArt,char *indDest,int status,struct coda* head){

    if(head==NULL){
        nodo *nuovo_nodo=malloc(sizeof(nodo));
        nuovo_nodo->x=codArt;
        nuovo_nodo->y=descrArt;
        nuovo_nodo->t=indDest;
        nuovo_nodo->z=status;
        nuovo_nodo->next=NULL;
        return nuovo_nodo;
    }else if(head->next!=NULL)
        enqueue(codArt,descrArt,indDest,status,head->next);
    else
        head->next=enqueue(codArt,descrArt,indDest,status,head->next);

}

void printList(struct coda* head){
    struct coda* thead=head;
    while(thead!=NULL){

        printf("--> %d ",thead->codiceArticolo);
        thead=thead->next;
    }
    printf("\n");

}

【问题讨论】:

  • 你能把剩下的代码贴出来吗?
  • 是的,我现在就添加到 OP 中

标签: c pointers queue adt


【解决方案1】:

您提供的代码似乎与您要求的相反:

main 中,您可以致电dequeue

nodo *newHead = dequeue(&testa);

你的意思是把老头还回去吗?

您的dequeue 函数采用指向头部的指针。它应该是一个指向指针的指针。

您似乎在dequeue 中分配内存。我现在看到在enqueue 中完成了分配,这是它应该发生的地方。 (顺便说一句,你认为什么时候应该释放内存?)

所以,我认为出队应该更像这样:

nodo* dequeue(nodo** head) {
    if(head==NULL) {
        return NULL; //nothing to extract
    }
    else {
        nodo* temp=*head;
        *head=temp->next;
        return temp;
    }
}

【讨论】:

  • 对不起,我应该解释一下 newHead 在这种情况下是无用的,我只是希望将弹出的元素返回到主元素。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
相关资源
最近更新 更多