反转单链表的两种写法

一、反转链表(循环写法)

#include
#include
struct node{
    int val;
    node *next;
};
void insert_tail(struct node **ptr, struct node *nd){
    while(*ptr != NULL) {
        ptr = &(*ptr)->next;
    }
    *ptr = nd;
}
void traverse(struct node *link, void (*print)(struct node *)) {
    while(link) {
        print(link);
        link = link->next;
    }
}
void show_node_info(struct node *nd) {
    printf("val is %d\n", nd->val);
}
struct node *search(struct node *link, int val) {
    while(link) {
        if(val == link->val) {
            return link;
        }
        link = link->next;
    }
    return NULL;
}
//循环反转
void reverse(struct node **ptr){
    struct node *tmp = *ptr;
    struct node *cur = *ptr;
    struct node *first = NULL;
    while(cur){
        tmp = cur->next;
        cur->next = first;
        first = cur;
        cur = tmp;
    }
    *ptr = first;
}

int main(){
    struct node *first = NULL;
    for(int i = 0; i < 3; i++) {
        struct node *nd = (struct node *)malloc(sizeof(struct node));
        nd->val = 10 + i;
        nd->next = NULL;
        insert_tail(&first, nd);
    }
    traverse(first, show_node_info);
    printf("========reverse========\n");
    reverse(&first);
    traverse(first, show_node_info);
    return 0;
}

运行结果:

反转单链表的两种写法_第1张图片

二、反转链表(递归写法)

#include
#include
struct node{
    int val;
    node *next;
};
void insert_tail(struct node **ptr, struct node *nd){
    while(*ptr != NULL) {
        ptr = &(*ptr)->next;
    }
    *ptr = nd;
}
void traverse(struct node *link, void (*print)(struct node *)) {
    while(link) {
        print(link);
        link = link->next;
    }
}
void show_node_info(struct node *nd) {
    printf("val is %d\n", nd->val);
}
struct node *search(struct node *link, int val) {
    while(link) {
        if(val == link->val) {
            return link;
        }
        link = link->next;
    }
    return NULL;
}
//递归反转
struct node *reverse(struct node *oldhead,struct node *newhead) {
   struct node *tmp = oldhead->next;
   oldhead->next = newhead;
   newhead = oldhead;
   if(tmp ==NULL){
       return newhead;
   }else{
       return reverse(tmp,newhead);
   }
}
int main(){
    struct node *first = NULL;
    for(int i = 0; i < 3; i++) {
        struct node *nd = (struct node *)malloc(sizeof(struct node));
        nd->val = 10 + i;
        nd->next = NULL;
        insert_tail(&first, nd);
    }
    traverse(first, show_node_info);
    printf("========reverse========\n");
    struct node *newhead = NULL;
    first = reverse(first, newhead);
    traverse(first, show_node_info);
    return 0;
}

运行结果:

反转单链表的两种写法_第2张图片 

 

你可能感兴趣的:(c语言,链表)