【问题标题】:Remove even numbers from queue从队列中删除偶数
【发布时间】:2016-01-31 18:39:13
【问题描述】:

我在 C 编程中尝试从队列中删除偶数时卡住了。代码如下:

我的队列数据结构:

typedef struct _listnode
{
    int data;
    struct _listnode *next;
} ListNode; // You should not change the definition of ListNode

typedef struct _linkedlist
{
    int size;
    ListNode *first;
} LinkedList;   // You should not change the definition of LinkedList

typedef struct _queue
{
    LinkedList list;
} Queue;

我是从我的主打来的:

case 3:
        deleteEven(&q); // You need to code this function
        printf("Result:\n");
        printList(&q.list);
        break;

首先,我尝试检查队列是否为空。然后我会得到链表头和模数为 2,如果得到 0 意味着它是偶数,然后我会将它从队列中出列。

但是,使用这些代码,当我尝试从队列中取出偶数时,它只是停止工作并且没有显示任何错误消息。

有人知道如何解决这个问题吗?提前致谢。

【问题讨论】:

    标签: c pointers linked-list queue nodes


    【解决方案1】:

    在您的函数deleteEvenwhile 循环中,您可以执行此操作-

    free(odd->list.first->data);                    //problem 1
    odd->list.first->data= odd->list.first->next;   //problem 2- assigning pointer type to int 
    

    问题 1- 但是您还没有为 odd->list.first->data 分配内存,它是一个整数变量。如果你尝试free 这样的事情可能会导致你的程序出错(你不应该 free 内存不是由 malloc 或类似的函数分配的)

    你将内存分配给odd,所以free指针odd

    即使你不应该在while 循环中使用free,因为你只分配一次内存。

    问题 2 - 您将指针类型分配给 int。这也可能是导致此错误的原因之一。

    你应该这样写循环 -

    while (!isEmptyQueue(odd)) {
        enqueue(que, odd->list.first->data);
        odd->list.first= odd->list.first->next;      // increment pointer 
    }
    free(odd);
    

    3.调用函数dequeue时-

     dequeue(que->list.first->data);
    

    int 已通过,但它需要 Queue *

    它的类型是int,但你从它返回NULL(返回-1或其他表示失败的东西)。

    【讨论】:

    • 对不起,你说的老是什么意思?我应该如何解决它?
    • @20Cents 哦,对不起,我的意思是odd 那里。编辑它。
    • 但是即使我取消了那行,程序仍然崩溃。你有什么想法吗?
    • @20Cents 是的,您还在循环中将指针类型分配给int,我已经对其进行了编辑。请看一下。
    • 很遗憾,没有。程序仍然崩溃
    猜你喜欢
    • 2017-02-06
    • 2018-12-11
    • 1970-01-01
    • 2012-12-17
    • 2012-08-17
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多