单链表的递归逆置

博主成功调试了递归实现的单链表逆置函数,体验到递归带来的乐趣,感叹编程如同修炼,乐趣无穷。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#define M 20
struct num
{
    int a;
    struct num *next;
};
struct num *reverse(struct num *head)
{
    struct num *p;
    p = head;
    if (p->next == NULL)
    {
        return p;
    }
    else
    {
        reverse(p->next);
        p->next->next = p;
        if (p == head)
        {
            p->next = NULL;
        }
    }
} 
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);
    prt(p);
    return 0;
}

结果

GDB

姜硬啊!rua!

2017/04/01 9:11

#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;
}

终于调好了,递归函数还是好玩啊。我欲成仙 快乐无边

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值