三、链表管理结构体

1
2
3
4
5
6
struct List
{
struct Node *head;
struct Node *tail;
int len;
};

1、初始化链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 初始化链表
struct List * init_list(void)
{
struct List *list = malloc(sizeof(struct List));
if(list == NULL) {
return NULL;
}

// 分配头节点空间
list->head = malloc(sizeof(struct Node));
if(list->head == NULL)
return NULL;

list->tail = list->head;
list->len = 0;

return list;
}

2、尾插

1
2
3
4
5
6
7
// 尾插
void insert_tail(struct Node *new, struct List * list)
{
list->tail->next = new;
list->tail = new;
list->len++;
}

3、遍历

1
2
3
4
5
6
7
8
9
10
11
12
// 遍历
void display_list(struct List * list)
{
struct Node *tmp = list->head->next;

for(int i=0; i<list->len; i++)
{
printf("%d->", tmp->data);
tmp = tmp->next;
}
printf("\n");
}