我正在尝试用 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;
Run Code Online (Sandbox Code Playgroud)
这是弹出功能:
/**
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白我做错了什么。(*list).head是 astruct cell_s所以我应该能够访问该属性next?但编译器不会让我这样做。
谢谢。
该head字段不是struct cell_s. 它是一个struct cell_s *,即指向 的指针struct cell_s。因此,您需要使用->运算符来取消引用和访问该成员。
list->head = list->head->next;
Run Code Online (Sandbox Code Playgroud)
另请注意,ptr->field比 更容易阅读(*ptr).field。
| 归档时间: |
|
| 查看次数: |
7337 次 |
| 最近记录: |