Search code examples
clinked-listreversesingly-linked-listfunction-definition

Why does the ReverseList function doesn't work?


this is the definition of the struct:

ElemTypeandstatusare both equal to int

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

the body:

            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;

this is the function:

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

after running the func,the linked list didn't be reversed.

How come? :)

the reverselist func doesn't work orz


Solution

  • In these nested if statements

            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");
    

    a non-empty list is reversed twice. The first one it is reversed in the condition of this if statement

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

    As the result is not INFEASIBLE then the next if statement gets the control

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

    and the list is reversed the second time.

    You need to assign the result of the function call to a variable and check the variable in the if statements.

    Pay attention to that the function does not return ERROR. So the second if statement in any case does not make sense.

    So you could just write

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

    or

    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");
    }
    //...