Jeswang's Blog

盲目跟随还是独立去做,To be or not to be?

LeetCode - Reverse Linked List II

| Comments

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.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 * 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 -

Comments