1. 代码逻辑不对
2. 申请了内存不释放
3. node *n = (node *)malloc(sizeof(node));
这里为什么不写成这样?
node *n = malloc(sizeof(node));
#include <stdio.h>
#include <stdlib.h>
//定义节点
typedef struct NODE
{
int data;
struct NODE* next;
}node;
//初始化链表
node *initLinkTable()
{
//创建一个头指针
node *head = NULL;
return head;
}
//展示列表元素
void displayEle(node* head)
{
while (head)
{
printf("链表元素:%d\n", head->data);
head = head->next;
}
}
//增加节点,尾插法
void addNode(node **head, int data)
{
//node *n = (node *)malloc(sizeof(node));
node *n = malloc(sizeof(node));
if (!n)
{
printf("申请内存失败");
return;
}
n->data = data;
n->next = NULL;
if(!*head) {*head = n; return;}
node* temp = *head;
while(temp->next) temp = temp->next;
temp->next = n;
/*
node* temp = head;
if (!head)
{
head = n;
}
else
{
while (temp)
{
temp = temp->next;
}
temp = n;
}
*/
}
void free_list(node *n) {
while(n) {
node *temp = n; n = temp->next;
free(temp);
}
}
int main(void)
{
node *head = initLinkTable();
for (int i = 0; i < 5; i++)
{
addNode(&head, i);
}
displayEle(head);//为什么无输出
free_list(head);
return 0;
}
|