#include <stdio.h> #include <malloc.h>
/* *带表头的单链表 */ struct list{ int num; struct list *next; };
void create_list(struct list **list,int num){
*list = (struct list *)malloc(sizeof(struct list)); if(NULL == *list){ printf("malloc failed\n"); } (*list)->next = NULL; (*list)->num = num; }
void destory_node(struct list *list) { if(list) free(list); }
void destory_list(struct list **head) { struct list *ptr = *head; struct list *ptr2;
if(NULL == *head) return; while(ptr){ ptr2 = ptr->next; printf("destory %d\n",ptr->num); destory_node(ptr); ptr = ptr2; } *head = NULL; }
void insert_list(struct list **head,struct list *new) { struct list *ptr = *head; struct list *backup;
if(NULL == head || NULL == new) return ;
while(ptr && ptr->num < new->num){ backup = ptr; ptr = ptr->next; }
if(ptr == *head){ new->next = *head; *head = new; } else{ new->next = backup->next; backup->next = new; }
}
void print_list(struct list *head) { struct list *ptr = head;
if(NULL == head) return ; while(ptr) { printf("%d\t",ptr->num); ptr = ptr->next; } printf("\n\n"); }
void print_list_convert(struct list *head) { //struct list *ptr = head; if(head){ print_list_convert(head->next); printf("%d\t",head->num); } }
void convert_list(struct list **head) { struct list *ptr = *head; struct list *index = ptr->next; struct list *backup;
while(index){ backup = index; index = index->next; backup->next = ptr; if(ptr == *head) ptr->next = NULL; ptr = backup; }
*head = ptr; }
int main(int argc,char *argv[]) { struct list *head,*new;
create_list(&head,-1);
create_list(&new,10); insert_list(&head,new);
create_list(&new,100); insert_list(&head,new);
create_list(&new,-90); insert_list(&head,new);
create_list(&new,80); insert_list(&head,new);
create_list(&new,5); insert_list(&head,new);
create_list(&new,-1000); insert_list(&head,new);
print_list(head); print_list_convert(head); printf("\n");
convert_list(&head); print_list(head);
destory_list(&head); print_list(head);
return 0; }
|