Question

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL

Difficulty:Medium

Category:Linked List

Analyze

Solution

/**
 * 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) {
    ListNode dummy(-1);
    dummy.next = head;

    ListNode* prev = &dummy;
    for (int i = 0; i < m - 1; ++i) {
      prev = prev->next;
    }

    ListNode* const start = prev;

    prev = start->next;
    ListNode* cur = prev->next;
    for (int i = m; i < n; ++i) {
      prev->next = cur->next;
      cur->next = start->next;
      start->next = cur;
      cur = prev->next;
    }
    return dummy.next;
  }
};
By guozetang            Updated: 2020-09-19 13:02:30

results matching ""

    No results matching ""