设有一个带头结点的链表,存储结构为
Typedef struct Node
{
ElemType data;
Struct Node *next;
}linklist;
其中data为整形数域,next为指针域,编写函数创建一个带头结点的单链表
给指针p开辟结点空间的语句为:p = (LinkList *)malloc(sizeof(LinkList));
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
struct node *next;
} LinkList;
LinkList *CreateList(int n)
{
int j=1;
LinkList *head,*p;
head=(LinkList*)malloc(sizeof(LinkList));
head->next=NULL;
for(;j<=n;j++){
p=(LinkList*)malloc(sizeof(LinkList));
scanf("%d",&(p->data));
p->next=head->next;
head->next=p;
}
return head;
}
void PrintList(LinkList *head)
{
LinkList *p = head->next;
while (p != NULL)
{
printf("%d,", p->data);
p = p->next;
}
}
int main()
{
LinkList *head;
int n;
scanf("%d", &n);
head = CreateList(n);
PrintList(head);
}