创建一个带头节点的单向链表,统计节点个数
程序员文章站
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");
}
}
上一篇: postgresql数据库复制表结构及数据到备份表
下一篇: 无人驾驶,哪五大领域能最快商业应用?