链表中的出队
我正在尝试让我的出队方法在 LinkedList ADT 的实现上发挥作用。但是,它是从队列的开头而不是末尾删除。有什么帮助吗?我是 C 新手,正在尝试将 java 练习移植到 C.. 它应该删除列表的最后一个节点。
这是我的出队方法:
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--;
}
这是尝试使最后一个节点出队时的输出:
=====================
|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
I'm trying to get my dequeue method working on my implementation of a 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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您已经看到的,linkedQueueDequeue 中的代码会弹出第一个条目,就像您想要一个堆栈 (LIFO) 一样,您可以将您的
temp
迭代到列表的末尾,然后删除它的temp- >next
:另请注意,考虑到第 2 行中的转换
(LinkedQueue*)q
,您的 Queue/LinkedQueue 实现有些奇怪。您确定需要该转换吗?我真的无法判断,因为您没有给我们 Queue 和 LinkedQueue 的定义。LinkedQueue
中是否还有一个->tail
?如果是这样,那么您不需要迭代,可以使用->tail
来定位temp
(当然:您必须更新->tail
到新的结尾)。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'stemp->next
: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? I cannot really tell because you did not give us the definitions of Queue and LinkedQueue. Is there maybe also a->tail
inLinkedQueue
? If so, then you dont need the iteration and can instead use->tail
to positiontemp
(and of course: you have to update->tail
to the new end).您的输出似乎是队列/先进先出的正确行为,因为要从列表中删除的第一个项目是添加到列表中的第一个项目。您是否尝试创建一个堆栈?
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. Are you trying instead to create a stack?