Reverse Linked List IIJun 27 '12
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
Given
1->2->3->4->5->NULL
, m = 2 and n = 4,
return
1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode(int x) : val(x), next(NULL) {}
- * };
- */
- class Solution {
- public:
- ListNode *reverseBetween(ListNode *head, int m, int n) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- nodeAtN = NULL;
- nodeAfterN = NULL;
- return revHelper(head, m - 1, n - 1);
- }
- ListNode *revHelper(ListNode *current, int m, int n) {
- if (!current) return NULL;
- ListNode *ret = current;
- if (m > 0) {
- current->next = revHelper(current->next, m - 1, n - 1);
- }
- else if (n > 0) {
- ListNode *currentNext = revHelper(current->next, m - 1, n - 1);
- currentNext->next = current;
- if (m == 0) {
- current->next = nodeAfterN;
- ret = nodeAtN;
- }
- }
- else if (n == 0) {
- nodeAtN = current;
- nodeAfterN = current->next;
- }
- return ret;
- }
- private:
- ListNode *nodeAfterN;
- ListNode *nodeAtN;
- };
Thanks Shawn, great quality code and nicely written.
ReplyDeleteHere's one that's pretty interesting too:
reversing singly linked list