欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

创建一个带头节点的单向链表,统计节点个数

程序员文章站 2022-03-15 17:33:20
...
#include    <stdio.h>
#include    <stdlib.h>
#define    N    8

typedef  struct list
{  
   int  data;
   struct list  *next;
} SLIST;

SLIST *creatlist(int  *a);
void outlist(SLIST  *);

void fun( SLIST  *h, int  *n)
{
   SLIST  *p;
   *n=0;
   p=h->next;
   while(p)
   {
      (*n)++;
      p=p->next;
   }
}

void main()
{
   SLIST  *head;
   int  a[N]={12,87,45,32,91,16,20,48}, num;
   head=creatlist(a);    
   outlist(head);
   fun(head, &num);
   printf("\nnumber=%d\n",num);
   system("pause");
}

SLIST *creatlist(int  a[])
{
   SLIST  *h,*p,*q;        
   int  i;
   h=p=(SLIST *)malloc(sizeof(SLIST));
   for(i=0; i<N; i++)
   {
      q=(SLIST *)malloc(sizeof(SLIST));
      q->data=a[i];  p->next=q;  p=q;
   }
   p->next=0;
   return  h;
}

void outlist(SLIST  *h)
{
   SLIST  *p;
   p=h->next;
   if (p==NULL)  printf("The list is NULL!\n");
   else
   {
      printf("\nHead ");
      do
      {  printf("->%d",p->data);  p=p->next;  }
      while(p!=NULL);
      printf("->End\n");
   }
}