-
建立一个带有头结点的单向链表,并将存储在数组中的字符依次转储到链表的各个结点中。
#include <stdio.h>
#include <stdlib.h>
struct node//瀹氫箟涓€涓粨鏋勪綋
{
int num;
struct node *next;
};
typedef struct node Node;
typedef struct node * Link;
int init(Link *head)//鍒濆鍖栭摼琛?{
*head = (Link)malloc(sizeof(Node));
if(!(*head))//鍒嗛厤涓嶆垚鍔熷氨閫€鍑? {
printf("error!\n");
return 0;
}
(*head)->next = NULL;
return 1;
}
void insert_head(Link *head,int n,int b[])//澶存彃娉?{
Link p;
int i;
*head = (Link)malloc(sizeof(Node));
if(!(*head))
{
printf("error!\n");
exit(-1);
}
(*head)->next = NULL;
for(i = 0; i < n; i++)//鏍稿績浠g爜锛屽皢鏁扮粍b鐨勫厓绱犳彃鍏? {
p = (Link)malloc(sizeof(Node));
p->num = b[i];
p->next = (*head)->next;
(*head)->next = p;
}
}
void display(Link head)//閬嶅巻閾捐〃
{
Link p = head->next;
while(p != NULL)
{
printf("%d",p->num);
p = p->next;
}
printf("\n");
}
int main()
{
Link head = NULL;
int b[10];
int i;
printf("input the arry!\n");
for(i = 0; i < 10; i++)
{
scanf("%d",&b[i]);
}
init(&head);
insert_head(&head,10,b);
display(head);
return 0;
}