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

 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,*q;
10     head=(node*)malloc(sizeof(node));
11     printf("input creat node's num\n ");
12     scanf("%d",&n);
13     q=head;
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         q->next=p;
20         p->next=NULL;
21         q=p;    
22     }
23     return head;
24     
25 }
26 print(node* head)
27 {
28     node* q;
29     q=head->next;
30     while(q)
31     {
32         if(q->next==NULL){printf("%d",q->info);}
33         else{printf("%d->",q->info);}
34         q=q->next; 
35     }
36 }
37 
38 int main()
39 {
40     node *head;
41     head=creat();
42     print(head);
43     return 0;
44 } 

思路:
创建头结点head
创建一个结构体指针q用来把整个链表穿起来;这是重点;q=head;
创建节点p:
q->next=p;
p->next=NULL;
q=p;

posted @ 2018-11-21 11:47  只争朝夕0  阅读(628)  评论(0编辑  收藏  举报