初始化链表
#include <stdio.h>
#include <stdlib.h>
typedef struct Link {
int elem;
struct Link* next;
}link;
link* initLink();
void display(link* p);
int main() {
printf("初始化链表为:\n");
link* p = initLink();
display(p);
return 0;
}
link* initLink() {
link* p = (link*)malloc(sizeof(link));
link* temp = p;
for (int i = 1; i < 5; i++) {
link* a = (link*)malloc(sizeof(link));
a->elem = i;
a->next = NULL;
temp->next = a;
temp = temp->next;
}
return p;
为了便于理解,我将上面的这个函数拆开重写了一遍,它其实就等价于下面这种形式:
link* initLink() {
link* p = (link*)malloc(sizeof(link));
link* temp = p;
link* a1 = (link*)malloc(sizeof(link));
a1->elem = 1;
a1->next = NULL;
temp->next = a1;
link* a2 = (link*)malloc(sizeof(link));
a2->elem = 2;
a2->next = NULL;
temp->next->next = a2;
link* a3 = (link*)malloc(sizeof(link));
a3->elem = 3;
a3->next = NULL;
temp->next->next->next = a3;
link* a4 = (link*)malloc(sizeof(link));
a4->elem = 4;
a4->next = NULL;
temp->next->next->next->next = a4;
link* a5 = (link*)malloc(sizeof(link));
a5->elem = 5;
a5->next = NULL;
temp->next->next->next->next->next = a5;
return p;
}
void display(link* p) {
link* temp = p;
while (temp->next) {
temp = temp->next;
printf("%d ", temp->elem);
}
printf("\n");
}