C 链表,使指针指向空列表

C 链表,使指针指向空列表,c,linked-list,sentinel,C,Linked List,Sentinel,我想制作一个带有哨兵节点的链表。列表结构必须只包含数据和下一个指针。我的问题是,不知何故,我必须创建一个指向逻辑空列表的空指针。所以基本上我必须创建一个空列表。下面的功能有点不好。请帮帮我 #include <stdio.h> #include <stdlib.h> typedef struct list { int data; struct list* next; } list; list* emptylist() { list* s1 = (

我想制作一个带有哨兵节点的链表。列表结构必须只包含数据和下一个指针。我的问题是,不知何故,我必须创建一个指向逻辑空列表的空指针。所以基本上我必须创建一个空列表。下面的功能有点不好。请帮帮我

#include <stdio.h>
#include <stdlib.h>

typedef struct list
{
    int data;
    struct list* next;
} list;
list* emptylist()
{
    list* s1 = (list*)malloc(1 * sizeof(list));
    list* s2 = (list*)malloc(1 * sizeof(list));
    s1->next = s2;
    s2->next= NULL;
    return s1;
}
#包括
#包括
类型定义结构列表
{
int数据;
结构列表*下一步;
}名单;
列表*emptylist()
{
list*s1=(list*)malloc(1*sizeof(list));
list*s2=(list*)malloc(1*sizeof(list));
s1->next=s2;
s2->next=NULL;
返回s1;
}

不要强制转换malloc,也不要使用sizeof(type)。相反,写入
list*s1=malloc(N*sizeof*s1)
指向逻辑空列表的空指针通常为
list*head=NULL有时,设计软件使
head
永远不为空是很有用的。在这种情况下,
emptylist()
应该分配一个节点
s1
,并设置
s1->next=NULL
。旁注:您调用的
list
看起来更像列表的元素/节点。尽管您可以将节点结构重用为列表结构,但更清楚的是:
typedef struct node{int data;struct node*next;}node并将列表定义为:
typedef struct list{struct node*head;}listemptylist
将执行以下操作:
list*s=malloc(1*sizeof(list));s->head=NULL;返回s(即不需要使用两个结构分配)。执行
list*s=malloc(1*sizeof(*s))有时被认为更安全和/或更惯用。