GLib有可以用作LIFO (堆栈)集合的数据类型吗?它确实列表、队列、哈希表等等,但我似乎找不到堆栈数据类型。
这里有一个垃圾堆栈类型,但是它的设计考虑到了一个特定的目的,而且它也是从2.48版本开始被废弃的。
在GLib中,什么可以用作堆栈?
发布于 2022-02-04 15:22:46
有点晚了,但是对于堆栈来说,一种更轻量级的方法是使用单链接列表类型GSList,它不需要显式容器对象。
GSList *stack = NULL;
// push:
stack = g_slist_prepend(stack, element);
// stack non-empty?
if (stack) { ... }
// peek head without popping:
element = stack->data;
// pop:
stack = g_slist_delete_link(stack, stack);然后,返回元素的正确"pop“的包装函数可能如下所示:
void *stack_pop(GSList **stackp) {
if (!*stackp)
return;
void *ret = (*stackp)->data;
*stackp = g_slist_delete_link(*stackp, *stackp);
return ret;
}
// ...
element = stack_pop(&stack); // returns NULL if stack is empty发布于 2017-07-20 10:24:49
从未使用过它,但是从文档中您应该可以使用一个双结束队列。要放到堆栈上,请使用g_queue_push_head(),从堆栈中弹出使用g_queue_pop_head(),请参阅:https://people.gnome.org/~desrt/glib-docs/glib-Double-ended-Queues.html
发布于 2019-06-21 06:14:08
我需要同样的东西,所以我写了这个小例子:
// An example stack in glib using a Queue. As this example uses
// integers, we make use of the glib GPOINTER_TO_UINT macros.
//
// Compile by:
// cc `pkg-config --cflags --libs glib-2.0` -o test-stack test-stack.c
#include <glib.h>
#include <stdio.h>
#include <stdint.h>
void pintqueue(GQueue *q)
{
int i;
printf("[%d] ", q->length);
GList *h = q->head;
for (i=0; i<q->length; i++) {
printf("%d ", (int)GPOINTER_TO_UINT(h->data));
h=h->next;
}
printf("\n");
}
void qintpush(GQueue *q, gint val)
{
g_queue_push_tail(q, GUINT_TO_POINTER((guint)val));
}
gint qintpop(GQueue *q)
{
if (q->length==0) {
// "Error handling"
g_message("Ooops! Trying to pop from an empty stack!");
return INT_MAX;
}
return (gint)(GPOINTER_TO_UINT(g_queue_pop_tail(q)));
}
gint main(int argc, char **argv)
{
GQueue q = G_QUEUE_INIT;
qintpush(&q, 34);
qintpush(&q, 42);
qintpush(&q, -1);
pintqueue(&q);
printf("Popped: %d\n", qintpop(&q));
pintqueue(&q);
for (int i=0; i<5; i++)
printf("Popped: %d\n", qintpop(&q));
exit(0);
}https://stackoverflow.com/questions/45211174
复制相似问题