以单向链表为例
创建链表
struct student {
int age;
int num;
struct student *next;
};
typedef struct student LIST;
LIST *CreateList(void)
{
LIST *h, *prev, *cur;
int i, n;
srand((int)time(0));
h = NULL;
for (i = 0; i < 8; i++) {
cur = (LIST *)malloc(sizeof(LIST));
cur->next = NULL;
cur->age = rand() % 100;
cur->num = i;
if (h == NULL) {
h = cur;
} else {
prev->next = cur;
}
prev = cur;
printf("Node[%d] = %d\n",i ,cur->age);
}
return h;
}
打印链表
void Displist(LIST *h)
{
int i;
LIST *p;
p = h;
while (p) {
printf("node[%d].age = %d\n", p->num, p->age);
p = p->next;
}
}
int main()
{
LIST *head;
printf("CreateList --------\n");
head = CreateList();
printf("Displist--------\n");
Displist(head);
printf("Displist-over-------\n");
}
songchong@srv-artek-pad:~/mytest/list$ gcc -o list-1 list-1.c
songchong@srv-artek-pad:~/mytest/list$ ./list-1
CreateList --------
Node[0] = 14
Node[1] = 35
Node[2] = 90
Node[3] = 61
Node[4] = 34
Node[5] = 60
Node[6] = 88
Node[7] = 65
Displist--------
node[0].age = 14
node[1].age = 35
node[2].age = 90
node[3].age = 61
node[4].age = 34
node[5].age = 60
node[6].age = 88
node[7].age = 65
Displist-over-------
songchong@srv-artek-pad:~/mytest/list$