diff options
Diffstat (limited to 'other/reverse_linked_list2.cpp')
-rw-r--r-- | other/reverse_linked_list2.cpp | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/other/reverse_linked_list2.cpp b/other/reverse_linked_list2.cpp new file mode 100644 index 0000000..dbbb261 --- /dev/null +++ b/other/reverse_linked_list2.cpp @@ -0,0 +1,26 @@ +#include "leetcode.h" + +class Solution { +public: + ListNode *reverseBetween(ListNode *head, int left, int right) { + if (head == NULL || head->next == NULL) + return head; + ListNode *tmp = new ListNode(-1); + tmp->next = head; + ListNode *itL = tmp, *preL = NULL; + for (int i = 0; i < left; i++) { + preL = itL; + itL = itL->next; + } + ListNode *itR = itL, *preR = preL; + for (int i = left; i <= right; i++) { + ListNode *forward = itR->next; + itR->next = preR; + preR = itR; + itR = forward; + } + preL->next = preR; + itL->next = itR; + return tmp->next; + } +}; |