Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active July 4, 2019 17:58
Show Gist options
  • Save yangpeng-chn/15fc67f287493674f05e987cf70a2d3f to your computer and use it in GitHub Desktop.
Save yangpeng-chn/15fc67f287493674f05e987cf70a2d3f to your computer and use it in GitHub Desktop.
In-place reversal of linked list
// iteration
ListNode* reverseList(ListNode* head) {
ListNode *pre = nullptr;
ListNode *cur = head;
while(cur){
ListNode *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
// recursion
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment