建立单链表

#include<stdio.h>
#include<stdlib.h>
typedef struct link 
{
    int date;
    struct link *next;
}appoint;
appoint *lianBiao(void);
int main()
{
    appoint *head=NULL;
    head=lianBiao();   /*虽然没有参数,但别忘记加括号*/
    while(head!=NULL)
    {
        printf("%d\n",head->date );
        head=head->next ;
     } 
    return 0;
 } 
appoint *lianBiao(void)/*返回的是指针,别忘了*号*/ 
 {
     appoint *head=NULL,*tail,*new; /*head指向头结点,tail指向尾结点,new指向新建的结点*/ 
     int number=0; /*number记录结点的个数*/ 
     while(1)
     {
         printf("请输入第%d个结点:",number+1);
         new=(appoint *)malloc(sizeof(appoint));
         scanf("%d",&new->date );
//         new->next=NULL;  /*每新让new指向一个空间,就让它的next指向空,这样尾结点的next没有再被指向,还是指向空的,少了这一步,链表将没有结尾*/ 
         if(new->date ==-1)
         {
             free(new);
            tail->next=NULL;  /*这个和上面那行,必须有一个存在,将尾结点的NEXT指向空。*/ 
             return head;
         }
         else
         {
             number++;
             if(number==1)
             {
                 head=new;
                 tail=new;
             }
             else
             {
                 tail->next =new;   /*把新结点连接起来*/ 
                 tail=new;             /*将tail指向尾结点*/ 
             }
         }
         
     }
 }

看了半个多月,终于理解了!

posted @ 2017-03-09 20:41  T.X  阅读(404)  评论(0编辑  收藏  举报