Created
July 4, 2018 15:10
-
-
Save jaldhar/34e7524840e50766f4083eb9dc244710 to your computer and use it in GitHub Desktop.
Reverse a singly-linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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