一个单向链表的结点包括数据域与指针域,对其数据域中的数据进行操作,需要用到结构体struct.
现有一道题是将a,b,c三个结点链成一个单向链表,并给各个结点的数据域赋值累加单向链表结点数据域中的数据作为函数值返回。源程序:
#include <stdio.h>
typedef int Elementtype;
typedef struct list
{
Elementtype data;
struct list *next;
}List;
int fun (List *h)
{
List *p;
int t = 0;
p = h;
while (p)
{
t = t + (*p).data;
p = (*p).next;
}
return t;
}
int main()
{
List a,b,c,*h;
a.data = 32;
b.data = 51;
c.data = 87;
c.next = '\0';
h = &a;
a.next = &b;
b.next = &c;
printf ("总和 = %d\n",fun(h));
return 0;
}