C语言 为什么ReverseList函数不起作用?

kxe2p93d  于 2023-04-11  发布在  其他
关注(0)|答案(1)|浏览(122)

这是struct的定义:
ElemTypestatus都等于int

typedef struct LNode{
    ElemType data;
    struct LNode *next;
}LNode, *LinkList;

身体:

case 15://ReverseList
                if(ReverseList(&L[i_num]) == INFEASIBLE) 
                    printf("The list doesn't exist!\n");
                else if(ReverseList(&L[i_num]) == ERROR) 
                    printf("The list is empty!\n");
                else
                    printf("Success!\n");

                getchar(); 
                getchar();
                break;

这是一个函数:

status ReverseList(LinkList *L)
//reverse the list
{
    if(L)
    {
        LinkList prev=NULL;
        LinkList cur=*L;
        LinkList next=NULL;
        while(cur)
        {
            next=cur->next;
            cur->next=prev;
            prev=cur;
            cur=next;
        }
        *L=prev;
        return OK;
    }
    else  
        return INFEASIBLE;
}

在运行func之后,链表没有被反转。
怎么会呢?:)
reverselist函数不工作或

qv7cva1a

qv7cva1a1#

在这些嵌套的if语句中

case 15://ReverseList
            if(ReverseList(&L[i_num]) == INFEASIBLE) 
                printf("The list doesn't exist!\n");
            else if(ReverseList(&L[i_num]) == ERROR) 
                printf("The list is empty!\n");
            else
                printf("Success!\n");

一个非空的列表被反转两次。第一次在if语句的条件下被反转

if(ReverseList(&L[i_num]) == INFEASIBLE) 
                printf("The list doesn't exist!\n");

如果结果不是INFEASIBLE,那么下一个if语句将获得控制权

else if(ReverseList(&L[i_num]) == ERROR) 
                printf("The list is empty!\n");

并且第二次反转该列表。
您需要将函数调用的结果赋给一个变量,并在if语句中检查该变量。
注意函数不会返回ERROR。所以第二个if语句在任何情况下都没有意义。
所以你可以写

case 15://ReverseList
    if(ReverseList(&L[i_num]) == INFEASIBLE) 
        printf("The list doesn't exist!\n");
    else
        printf("Success!\n");

case 15://ReverseList
{
    status result = ReverseList(&L[i_num]);

    if( result == INFEASIBLE) 
        printf("The list doesn't exist!\n");
    else if( result == ERROR) 
        printf("The list is empty!\n");
    else
        printf("Success!\n");
}
//...

相关问题