建立链表
建立链表
以下代码用c语言建立链表。把建立链表作为函数,通过调用函数建立链表。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node; //struct Node = Node
typedef struct Node* LinkList; //struct Node* = LinkList
void CreateListTail(LinkList* L, int n) { //LinkList A,A -> Node
//LinkList* L, L -> A
//*L=A -> Node
LinkList p, r;
int i;
*L = (LinkList)malloc(sizeof(Node)); //*L = head
//right: a point -> O, space of O is malloc
r = *L;
for (i = 0; i < n; i++) {
p = (LinkList)malloc(sizeof(Node));
p->data = i;
r->next = p;
r = p;
}
r->next = NULL;
}
int main() {
LinkList* List =(LinkList*)malloc(sizeof(Node*)); //*List = head ->headNode
//distribute the same space of a point
int number = 10;
CreateListTail(List, number);
LinkList p = *List;
while (p->next != NULL)
{
printf("%-5d", p->next->data); //headNode contains no data
p = p->next;
}
printf("\n");
return 0;
};
输出结果:
0 1 2 3 4 5 6 7 8 9
难点在于,创建链表的函数使用的变量是指向指针的指针,而且开辟空间时,需要注意开辟Node大小的空间还是指针大小的空间。