2

I am creating a recursive function to reverse a linked list.

class LinkedList {

    node *head;

  public:
    node *reverse(/* Here, I want to pass the head as a default argument */);
}

I have tried to do node *reverse(node *nd = this->head) but it raises the following error:

'this' may only be used inside a nonstatic member function

Why is this happening? How can I achieve my goal?

Priyanshul Govil
  • 518
  • 5
  • 20

2 Answers2

2

You might create overloads:

class LinkedList {
    node *head;
public:
    node *reverse(node*);
    node *reverse() { return reverse(head); }
    // ...
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

The problem is, the default argument is supposed to be provided from the caller context, where this doesn't exist.

You can provide an overload.

class LinkedList {

    node *head;

  public:
    node *reverse(...);
    node *reverse() { return reverse(this->head); }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405