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;}list然后,emptylist
将执行以下操作:list*s=malloc(1*sizeof(list));s->head=NULL;返回s代码>(即不需要使用两个结构分配)。执行list*s=malloc(1*sizeof(*s))代码>有时被认为更安全和/或更惯用。