Created
July 5, 2019 16:17
-
-
Save yangpeng-chn/31344665eb93dca4e992b79f22a52826 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
ListNode *reverseBetween(ListNode *head, int m, int n) { | |
ListNode dummy(-1), *pre = &dummy; | |
dummy.next = head; | |
for (int i = 0; i < m - 1; ++i) pre = pre->next; | |
ListNode *cur = pre->next; | |
for (int i = m; i < n; ++i) { | |
ListNode *t = cur->next; | |
cur->next = t->next; | |
t->next = pre->next; | |
pre->next = t; | |
} | |
return dummy.next; | |
} | |
// Use regular linked list reversal | |
ListNode* reverseBetween(ListNode* head, int m, int n) { | |
ListNode *prev = nullptr, *cur = head; | |
for(int i = 1; i < m; i++){ | |
prev = cur; | |
cur = cur->next; | |
} | |
ListNode *beforeStart = prev, *start = cur; | |
for(int i = m; i <= n; i++){ //regular reversal | |
ListNode* tmp = cur->next; | |
cur->next = prev; | |
prev = cur; | |
cur = tmp; | |
} | |
start->next = cur; | |
if(m == 1) head = prev; | |
else beforeStart->next = prev; | |
return head; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment