Yi's Blog

思绪来得快,去得也快

LeetCode - Reverse Linked List II

LeetCode - Reverse Linked List II 解题说明

题目:

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

For example:

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.

代码实现过程:

链表题目的代码无论怎么写读起来都很费想象力,还是画一下理解起来比较容易了。

Reverse_Linked_List_II

代码:

/**
 * 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) {

    if (head == NULL || head->next == NULL || m == n) {
      return head;
    }

    ListNode *pre = NULL;
    ListNode *cur = head;

    for (int j = 1; j < m; j++) {
      pre = cur;
      cur = cur->next;
    }

    ListNode *beginNode;
    ListNode *firstNodeToExchange;

    beginNode = pre;
    firstNodeToExchange = cur;

    ListNode *tmp;
    tmp = cur->next;

    for (int i = m; i < n; i++) {
      pre = cur;
      cur = tmp;
      tmp = cur->next;

      cur->next = pre;
    }

    firstNodeToExchange->next = tmp;

    if (beginNode != NULL) {
      beginNode->next = cur;
      return head;
    } else {
      return cur;
    }
  }
};

- EOF -