Skip to main content
1 of 3
David K
  • 1.2k
  • 7
  • 8

It might be helpful to have a little more context for this code, to answer questions such as why you don't do something like this:

#include <list>
...
  std::list<int> my_list;
  ... put something in my_list to make a non-trivial test ...
  show_list(my_list);
  my_list.reverse();
  show_list(my_list);

There's also a singly-linked list, std::slist, if you want to avoid the double-linking of std::list, although I've previously found std::slist not as portable as std::list. (That is, not everyone's implementation of STL seemed to provide it.)

If it's really worth creating your own linked list, how about making a class called something like List containing objects of type Node, or implement these as templates List and Node as others have recommended. Then you can make reverse() be a member function of List so that you can write something like:

List<T> my_list;
... other code ...
my_list.reverse();

A member function returning void would be my preferred way to modify an object "in place"--the function doesn't return anything, and in this case it doesn't even have parameters to play with, so it's clear the ONLY thing it can do is to modify the original list. And notice that that's how list reversal is implemented in STL.

David K
  • 1.2k
  • 7
  • 8