代码包含:
- 创建空链表;
- 链表添加节点;
- 链表打印;
- 链表删除。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
typedef struct LIST_NODE NODE;
typedef struct LIST_NODE *LIST;
typedef double DATA_TYPE;
struct LIST_NODE
{
DATA_TYPE element;
NODE *next;
};
NODE *creat_empty_list(void)
{
NODE *p;
p=malloc(sizeof(NODE));
if(p==NULL)
return NULL;
p->next=NULL;
printf("Empty list is created.\n");
return p;
}
int add_node2list(LIST list,DATA_TYPE element)
{
NODE *p,*tmp;
tmp=malloc(sizeof(NODE));
if(tmp==NULL) return -1;
tmp->element=element;
tmp->next=NULL;
p=list;
while(p->next!=NULL)
{
p=p->next;
}
p->next=tmp;
return 0;
}
void print_list(LIST list)
{
if(list->next==NULL)
{
printf("Empty List.\n");//empty list.
return;
}
NODE *p;
p=list->next;
while(p->next!=NULL)
{
printf("%f\n",(double)p->element);
p=p->next;
}
printf("%f\n",(double)p->element);//last node.
}
void delete_list(LIST list)
{
NODE *p,*tmp;
p=list;
while(p->next!=NULL)
{
tmp=p;
p=p->next;
free(tmp);
}
free(p);//last node.
printf("List has been deleted.\n");
}
int main()
{
LIST list;
list=creat_empty_list();
for(int i= 0;i < 10;i ++)
{
add_node2list(list,(DATA_TYPE)i);
}
print_list(list);
delete_list(list);
return 0;
}