How to scroll through a chained list from the last position?

Asked

Viewed 1,770 times

0

I have a question about a chained list in C. The exercise is a function that takes as parameter the initial node of the chained list and the position x (counting backwards). With this, I have to go through and find the position, return the value of the corresponding node.

I’ve done it so far:

struct Node
{
    int data;
    struct Node *next;
}
/*-------------------------------------------------*/

int GetNode(Node *head,int positionFromTail)
{
    struct Node* fimNodo;
    while(head->next!=NULL){
        head->next=next;
        if(head->next==NULL){

            fimNodo->data=head->data;
            fimNodo->next=head->next;
        }

    }
    while(positionFromTail!=0){
        fimNodo->next=*next;
        positionFromTail--;
        if(positionFromTail==0){
            return fimNodo->data;
        }
    }
}

You are making a mistake in this role. Could someone help me?

Note: Exercise is only this function and does not require the main function...

The errors that are occurring are:

cannot resolve overloaded function ‘next’ based on conversion to type ‘Node*’


cannot convert ‘Node’ to ‘Node*’ in assignment
  • could specify which error is occurring?

  • cannot resolve overloaded function ‘next’ based on conversion to type ‘Node*’, base operand of ‘->’ has non-pointer type ‘Node’, base operand of ‘->’ has non-pointer type ‘Node’, base operand of ‘->’ has non-pointer type ‘Node’ , this occurs from the second while.

  • Friend, put the error message editing the question. It’s horrible to read code in the comments

  • 1

    I saw that you updated the code... I edited it now to format it better. But I wonder where the variable is initialized next, used at the beginning of loops. If I try to compile, it will give undeclared variable...

2 answers

1


The error of the remark, basically, is that you declared struct Node fimNodo; as a static variable, and not as a pointer.

Use:

struct Node* fimNodo;

to use fimNodo->next out fimNodo->data.

0

Guys I got!!!

The code went like this:

int GetNode(struct Node *head, int positionFromTail)
{
    int x = 0, y = 2;
    struct Node *fimNodo = head;

    if (fimNodo == NULL) {
        return -1;
    }

    while (fimNodo != NULL) {
        fimNodo = fimNodo->next;
        x++;
    }

    x = x - positionFromTail;
    fimNodo = head;

    while (y <= x) {
        fimNodo = fimNodo->next;
        y++;
    }   

    return fimNodo->data;
}

OBS: I briefly added 2 counters (x and y). One to go through the chained list to see the total positions (x) and one to find the position needed. I did the comparison to see if the list was empty, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.