前插法创建带头节点的单链表

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct{
 4     int info;
 5     struct node *next;
 6 }node;
 7 node* creat(){
 8     int n,i;
 9     node *head;
10     head=(node*)malloc(sizeof(node));
11     head->next=NULL;
12     printf("input creat node's num\n ");
13     scanf("%d",&n);
14     for(i=0;i<n;i++){
15         node *p;
16         p=(node*)malloc(sizeof(node));
17         printf("input node value\n");
18         scanf("%d",&p->info);
19         p->next=head->next;
20         head->next=p;
21     }
22     return head;
23     
24 }
25 print(node* head)
26 {
27     node* q;
28     q=head->next;
29     while(q)
30     {
31         if(q->next==NULL){printf("%d",q->info);}
32         else{printf("%d->",q->info);}
33         q=q->next; 
34     }
35 }
36 
37 int main()
38 {
39     node *head;
40     head=creat();
41     print(head);
42     return 0;
43 }

思路:

创建头结点head:head的指针域附为空

创建节点:p

P->next=head->next // p->next域附为空

head->next=p // 把p节点连接到头指针后

原文地址:https://www.cnblogs.com/Thegonedays/p/9998052.html