直接上代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct list{
int num;
struct list *next;
}list_t;
//链表头初始化
list_t *list_init()
{
list_t *head = (list_t *)malloc(sizeof(list_t));
if(head == NULL)
return NULL;
head->num = 0;
head->next = NULL;
return head;
}
//尾部追加
void append_tail(list_t *h,int num)
{
list_t *one = (list_t *)malloc(sizeof(list_t));
if(one == NULL)
return;
one->num = num;
one->next = NULL;
#if 1
list_t *end;
end = h;
while(end->next != NULL)
end = end->next;
end->next = one;
#else
//二级指针尾部追加
list_t **link;
link = &h->next;
while(*link)
link = &(*link)->next;
*link = one;
#endif
}
//头部追加
void append_top(list_t *h,int num)
{
list_t *one = (list_t *)malloc(sizeof(list_t));
if(one == NULL)
return;
one->num = num;
//以下两行不可调换,防止无节点时产生错误
one->next = h->next;
h->next = one;
}
//遍历链表
void trave_list(list_t *h)
{
list_t *i;
for(i=h->next;i!=NULL;i=i->next)
printf("%x ",i->num);
printf("\n");
}
//删除链表
void delete_list(list_t *h)
{
#if 0
list_t *i;
list_t *j;
for(i=h->next;i!=NULL;i=j)
{
j = i->next;
h->next = i->next;
free(i);
}
#else
//二级指针删除链表
list_t *entry;
list_t **link = &h->next;
while(*link)
{
entry = *link;
#if 0
//删除所有节点
*link = entry->next; //将头节点指向<删除节点>的后一个节点
free(entry);
#else
//一个节点不删除
link = &entry->next;
#endif
}
#endif
}
int main()
{
int num = 0;
list_t *head = list_init();
while(1)
{
scanf("%d",&num);
if(num == -1)
break;
append_tail(head,num);
}
trave_list(head);
delete_list(head);
trave_list(head);
return 0;
}