#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node {
int val;
struct node *next;
}Node;
void free_list(Node *list)
{
Node *tmp = NULL;
while(list)
{
tmp = list->next;
free(list);
list = tmp;
}
}
void print_list(Node *list)
{
while(list)
{
printf("%u ", list->val);
list = list->next;
}
printf("\n");
}
Node *create_list(void)
{
int len, i;
Node *list = NULL;
Node **pcur = NULL;
Node *tmp = NULL;
printf("Please input length and elements:");
scanf("%u", &len);
pcur = &list;
for(i=0; i<len; i++)
{
tmp = (Node *)malloc(sizeof(Node));
if(NULL == tmp)
{
free_list(list);
printf("malloc error!!\n");
return NULL;
}
memset(tmp, 0, sizeof(Node));
scanf("%u", &tmp->val);
*pcur = tmp;
pcur = &(*pcur)->next;
}
return list;
}
int main(int argc, char *argv[])
{
Node *list = NULL;
list = create_list();
print_list(list);
print_list(list);
free_list(list);
return 0;
}
简单单链表的 创建 打印 和 释放
最新推荐文章于 2023-09-24 11:51:51 发布