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
  • 468
  • 2
  • 17

2 Answers2

2

You might create overloads:

class LinkedList {
    node *head;
public:
    node *reverse(node*);
    node *reverse() { return reverse(head); }
    // ...
};
Jarod42
  • 190,553
  • 13
  • 166
  • 271
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
  • 163,662
  • 15
  • 289
  • 382