鱼C论坛

 找回密码
 立即注册
查看: 1545|回复: 1

[已解决]大佬们帮我看一下Reverse函数那哪出错了,函数实现的功能是链表逆转。

[复制链接]
发表于 2021-6-28 15:29:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
int main(){
struct student *head,*p,*q,*n,*test;
struct student * Reverse(struct student * L);
    int m=0;
    p=q=(struct student *)malloc(sizeof(struct student));
    scanf("%d%d",&p->num,&p->score);
    head=NULL;
    while(p->num!=0)
    {
        m=m+1;
        if(m==1)
            head=p;
        else{
        q->next=p;
        q=p;
        p=(struct student *)malloc(sizeof(struct student));
        scanf("%d%d",&p->num,&p->score);
    }}
    q->next=NULL;
    test=Reverse(head);
}
struct student * Reverse(struct student * L){
    if(L==NULL) return NULL;
    if(L->next==NULL) return L;

    struct student *p,*r;
    p=L;
    r=p->next;
    p->next=NULL;
    while(r!=NULL){
       r->next=p;
        p=r;
        r=r->next;
}

return r;
}
最佳答案
2021-6-28 16:58:06
struct NODE *sll_reverse(struct NODE *first)
{
    Node *newfirst;
    Node *p = first;
    Node *q = first;
    if(first == NULL)
        return NULL;

//让p指向最后一个元素,q指向倒数第二个
    while(p->link != NULL){
        q = p;
        p = p->link;
    }
    newfirst = p;

//箭头反转
    while(q != first){
        p->link = q;
        p = q;
    }
    q->link = NULL;
    return newfirst;    
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-6-28 16:58:06 | 显示全部楼层    本楼为最佳答案   
struct NODE *sll_reverse(struct NODE *first)
{
    Node *newfirst;
    Node *p = first;
    Node *q = first;
    if(first == NULL)
        return NULL;

//让p指向最后一个元素,q指向倒数第二个
    while(p->link != NULL){
        q = p;
        p = p->link;
    }
    newfirst = p;

//箭头反转
    while(q != first){
        p->link = q;
        p = q;
    }
    q->link = NULL;
    return newfirst;    
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 16:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表