#include <stdio.h>
typedef struct grade
{
int score;
struct grade *next;
}NODE;
NODE *list_creat();
int list_insert(NODE* head,NODE *pNew);
int list_delete_item(NODE *list,NODE *item);
void list_destory(NODE *list);
void showList(NODE *head);
void showList(NODE *head)
{
NODE *p =NULL;
for(p = head->next;p!=NULL;p = p->next)
{
printf("%d ",p->score);
}
printf("\n");
}
void list_destory(NODE *list)
{
NODE *delete = NULL;
while(NULL != list->next)
{
delete = list->next;
list->next = delete->next;
free(delete);
}
free(list);
}
NODE *list_creat()
{
NODE *head = NULL;
NODE *tail = NULL;
int score = 0;
//带头节点的链表创建: 头节点的数据域不能有值,
head = (NODE*)malloc(sizeof(NODE));
if(NULL == head)
{
return NULL;
}
head->next = NULL;
tail = head;
NODE *pNew = NULL;
pNew = (NODE *)malloc(sizeof(NODE));
if(NULL == pNew)
{
return NULL;
}
score = 99;
pNew->score = score;
pNew->next = NULL;
tail->next = pNew;
tail = pNew;
return head;
}
int list_insert_tail(NODE* list,NODE *pNew)
{
NODE *last = list->next;
while(last)
{
if(last->next == NULL)
{
pNew->next = last->next;
last->next = pNew;
break;
}
last = last->next;
}
}
int list_insert(NODE* head,NODE *pNew)
{
//带头节点的头插法
pNew->next = head->next;
head->next = pNew;
return 0;
}
int list_delete_item(NODE *list,NODE *item)
{
NODE *head = list;
if(item == head)
{
head->next = item->next;
return ;
}
while(head)
{
if(item == head->next)
{
break;
}
head = head->next;
}
if(head)
{
head->next = item->next;
}
free(item);
return 0;
}
int main()
{
printf("list test:\n");
NODE *new_node = NULL;
NODE *new_node1 = NULL;
NODE *list = NULL;
list = list_creat();
printf("one node :");
showList(list);
new_node = (NODE *)malloc(sizeof(NODE));
if(NULL == new_node)
{
return -1;
}
new_node ->score= 100;
list_insert(list,new_node);
printf("one and two node:");
showList(list);
new_node1 = (NODE *)malloc(sizeof(NODE));
if(NULL == new_node1)
{
return -1;
}
new_node1->score= 98;
//list_insert(list,new_node1); //头插
list_insert_tail(list,new_node1); //尾插
printf("All the nodes :");
showList(list);
list_delete_item(list,new_node1); //删除节点
printf("after delete third node :");
showList(list);
list_destory(list);
return 0;
}