我正在尝试用 C 实现堆栈/链表。我在堆栈的 pop
函数上苦苦挣扎。
这是我的堆栈/链表实现的样子:
// a cell
struct cell_s
{
void *elem;
struct cell_s *next;
};
typedef struct cell_s cell_t;
// the list is a pointer to the first cell
struct linkedlist_s
{
struct cell_s *head;
int len;
};
typedef struct linkedlist_s linkedlist_t;
这是弹出函数:
/**
* Pop remove and return the head
*/
cell_t *pop(linkedlist_t *list)
{
if ((*list).len == 0) {
// we cannot pop an empty list
return NULL;
}
else
{
cell_t* tmp = (*list).head;
(*list).head = (*list).head.next; // <-- error occurs here
(*tmp).next = NULL;
return tmp;
}
}
我不明白我做错了什么。 (*list).head
是一个 struct cell_s
所以我应该能够访问属性 next
?但是编译器不允许我这样做。
谢谢。
最佳答案
head
字段不是 struct cell_s
。它是一个 struct cell_s *
,即指向 struct cell_s
的指针。因此,您需要使用 ->
运算符来取消引用和访问成员。
list->head = list->head->next;
另请注意,ptr->field
比 (*ptr).field
更易于阅读。
关于c - 表达式必须具有结构或 union 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520351/