递归销毁单链表

#include 
#include 
#include
struct node{
    int val;
    struct node *next;
};
void insert_head(struct node **ptr,struct node *new){
    new->next = *ptr;
    *ptr = new;
}
void insert_tail(struct node **ptr,struct node *new){
    while(*ptr != NULL){
        ptr = &(*ptr)->next;
    }
    *ptr = new;
}
void insert(struct node *pos,struct node *new){
    new->next = pos->next;
    pos->next = new;
    int tmp = pos->val;
    pos->val = new->val;
    new->val = tmp;
}
//链表的转置
void reverse(struct node **ptr){
    struct node *cur = *ptr;
    struct node *first = NULL;
    struct node *tmp;
    while(cur){
        tmp = cur->next;
        cur->next = first;
        first = cur;
        cur = tmp;
    }
    *ptr = first;
}

//递归销毁链表
void delete_list(struct node **ptr){
    if(*ptr == NULL){
        return;
    }
    delete_list(&(*ptr)->next);
    free(*ptr);
}
void traverse(struct node *ptr){
    struct node *tmp = ptr;
    while(tmp != NULL){
        printf("val is %d\n", tmp->val);
        tmp = tmp->next;
    }
}
int main(){
    struct node *first = NULL;
    for(int i = 0; i < 5; i++){
        struct node *nd  = (struct node *)malloc( sizeof(struct node));
        nd->next = NULL;
        nd->val = i + 10;
        insert_tail(&first, nd);
    }
    traverse(first);
    delete_list(&first);
    return 0;
}

你可能感兴趣的:(链表)