Last active
July 4, 2019 17:58
-
-
Save yangpeng-chn/15fc67f287493674f05e987cf70a2d3f to your computer and use it in GitHub Desktop.
In-place reversal of 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
// 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