Skip to content

Instantly share code, notes, and snippets.

@jaldhar
Created July 4, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaldhar/34e7524840e50766f4083eb9dc244710 to your computer and use it in GitHub Desktop.
Save jaldhar/34e7524840e50766f4083eb9dc244710 to your computer and use it in GitHub Desktop.
Reverse a singly-linked list
// Assuming a linked list that looks like this:
template <typename T>
class List {
public:
// ...
void reverse();
private:
struct Node {
T value_;
Node* next_;
};
Node* head_;
};
template <typename T>
void List<T>::reverse() {
// 0 or 1 items in the list
if (head_ == nullptr || head_->next_ == nullptr) {
return;
}
Node* reversed = nullptr;
auto current = head_;
while (current != nullptr) {
Node* next = current->next_;
current->next_ = reversed;
reversed = current;
current = next;
}
head_ = reversed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment