天天看点

链表翻转

使用了两种方法,递归法 和 非递归法

#include <stdio.h>
#include <stdlib.h>


struct node
{
    int data;
    struct node * next;
};

void push(struct node ** head_ref, int new_data)
{
    struct node * new_node  = (struct node *) malloc(sizeof(struct node));

    new_node->data = new_data;

    new_node->next = *head_ref;
    *head_ref = new_node;

}


void printlist( struct node * head)
{
    struct node * tmp = head;

    while(tmp != NULL)
    {   
        printf("%d , tmp->data);

        tmp = tmp->next;
    }   
}


void reverse(struct node ** head_ref)
{
    struct node * prev = NULL;
    struct node * cur = * head_ref;
    struct node * next = NULL;

    while( cur != NULL)
    {
        next = cur->next;
        cur->next = prev;

        prev = cur;
        cur = next;
    }   

    *head_ref = prev;

}

// 使用递归的方法
struct node * reverse_recall(struct node *head)
{
    //最后一个节点作为头部返回
    if (head == NULL || head->next == NULL)
        return head;

    // head->next 表示剩下的部分
    struct node *new_head = reverse_recall(head->next);

    head->next->next = head;
    head->next = NULL;

    return new_head;

}


int main()
{
    struct node *head = NULL;

    push(&head , 4);
    push(&head , 5);
    push(&head , 6);
    push(&head , 7);
    push(&head , 8);

    printlist( head );

    reverse(&head);
    printf("\n");

    printlist( head );

    head = reverse_recall( head );

    printf("\n");

    printlist( head );


}