链表逆序——迭代法、递归法

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

typedef struct List
{
    int data;
    struct List *next;
} * List, node;

List CreatList(List head,int e);
void Print(List head);
List Back1(List head);     //迭代逆序
List Back2(List head);
int main(void)
{
    List list;
    for (int i = 1;i<6;i++){
        list = CreatList(list,i);
    }
    Print(list);
    list = Back1(list);
    Print(list);
    list = Back2(list);
    Print(list);
}

List CreatList(List head, int e)
{
    List p, q = head;
    p = (List)malloc(sizeof(node));
    if (head == NULL)
    {
        p->data = e;
        head = p;
        head->next = NULL;
    }
    else
    {
        p->data = e;
        p->next = q;
    }
    return p;
}

void Print(List head)
{
    List p;
    while(p != NULL){
        printf("%3d",p->data);
        p = p->next;
    }
    printf("\n");
}

List Back1(List head)         //迭代逆序
{
    List prev = NULL,next,cur = head;
    while(cur->next!=NULL){
        next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next; 
    }
    cur->next = prev;
    return cur;
}

List Back2(List head)          //递归逆序
{
    if(head==NULL||head->next==NULL)
    {
        return head;
    }
    List new_head = Back2(head->next);
    head->next->next=head;
    head->next = NULL;
    return new_head;
}

 

posted @ 2021-05-11 16:43  书亦非书  阅读(100)  评论(0)    收藏  举报