简体   繁体   English

在LinkedList中出队

[英]Dequeueing in a LinkedList

I'm trying to get my dequeue method working on my implementation of a LinkedList ADT. 我正在尝试让我的出队列方法在LinkedList ADT的实现上工作。 However, it is removing from the beginning of the queue instead of the end. 但是,它是从队列的开头而不是结尾处删除的。 Any help with this? 有什么帮助吗? I'm new to C, and am trying to port a java exercise over to C.. It's supposed to remove the last node of the list. 我是C语言的新手,正在尝试将Java练习移植到C语言。应该删除列表的最后一个节点。

Here's my dequeue method: 这是我的出队方法:

static void linkedQueueDequeue(Queue* q) {
    LinkedQueue *lq = ((LinkedQueue*)q->privateData);
    Node* temp = lq->head->next;
    lq->head->data = lq->head->next->data;
    lq->head->next = temp->next;
    free(temp);
    lq->size--;


}

Here's the output when trying to dequeue last node: 这是尝试使最后一个节点出队时的输出:

=====================
|Testing LinkedQueue|
=====================
adding 1 to first node
adding 2 to second node
adding 3 to third node
adding 4 to fourth node
[1,2,3,4]
dequeue last node
should print [1,2,3]
[2,3,4]
return first node
peek: 2
what's the size?
size: 3

As you saw already, the code in linkedQueueDequeue pops the first entry as if you wanted a stack (LIFO), you can iterate your temp to the end of the list, then remove it's temp->next : 如您所见,linkedQueueDequeue中的代码会弹出第一个条目,就像您要堆栈(LIFO)一样,您可以将temp循环到列表的末尾,然后将其删除temp->next

static void linkedQueueDequeue(Queue* q) {
    LinkedQueue *lq = ((LinkedQueue*)q->privateData);
    Node* temp = lq->head->next;
    while(temp->next) temp = temp->next;
    free(temp->next);
    temp->next = 0;
    lq->size--;
}

Also note, that there ist something slightly odd about your Queue/LinkedQueue implementation considering the conversion (LinkedQueue*)q in line 2. Are you sure you need that cast? 还要注意,考虑到第2行中的转换(LinkedQueue*)q ,您的Queue / LinkedQueue实现有些奇怪。确定要进行(LinkedQueue*)q转换吗? I cannot really tell because you did not give us the definitions of Queue and LinkedQueue. 我真的不能说出来,因为您没有给我们Queue和LinkedQueue的定义。 Is there maybe also a ->tail in LinkedQueue ? LinkedQueue是否也可能有一个->tail If so, then you dont need the iteration and can instead use ->tail to position temp (and of course: you have to update ->tail to the new end). 如果是这样,则您不需要迭代,而可以使用->tail来定位temp (当然:您必须将->tail更新到新的一端)。

Your output appears to be the correct behavior for a queue/FIFO in that the first item to be removed from the list is the first item that was added to the list. 您的输出似乎是队列/ FIFO的正确行为,因为要从列表中删除的第一项是添加到列表中的第一项。 Are you trying instead to create a stack? 您是否正在尝试创建堆栈?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM