逆置单链表

#include <stdio.h>
#include <stdlib.h>
#define M 20
struct num
{
    int a;
    struct num *next;
};
struct num *reverse(struct num *head, struct num *lhead, struct num *nhead)
{
    struct num *p, *q;
    p = head;
    if (p->next == NULL)
    {
        nhead = p;
    }
    else
    {
        nhead = reverse(p->next, lhead, nhead);
        p->next->next = p;
        if (p == lhead)
        {
            p->next = NULL;
        }
    }
    return nhead;
}
struct num *creat(int n)
{
    struct num *phead, *ptail, *pnew;
    pnew = (struct num *)malloc(sizeof(struct num));
    scanf("%d", &pnew->a);
    phead = ptail = pnew;
    for (int i = 1; i < n; ++i)
    {
        pnew = (struct num *)malloc(sizeof(struct num));
        scanf("%d", &pnew->a);
        ptail->next = pnew;
        ptail = pnew;       
    }
    ptail->next = NULL;
    return phead;
}
void prt(struct num *head)
{
    struct num *p;
    p = head;
    while(p != NULL)
    {
        printf("%d->", p->a);
        p = p->next;
    }
    printf("NULL\n");
}
int main(int argc, char const *argv[])
{
    struct num *p;
    int n = 0;
    scanf("%d", &n);
    p = creat(n);
    p = reverse(p, p, p);
    prt(p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jiaochiwuzui/article/details/81201372
今日推荐