首页 > 代码库 > 【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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         if (m == n) return head;
13         ListNode dummy(-1);
14         dummy.next = head;
15         ListNode *p = &dummy;
16         for (int i = 0; i < m - 1; ++i) {
17             p = p->next;
18         }
19         //p指向第m个结点的前一个结点
20         ListNode *t = p->next, *q = t->next;
21         //t指向已经reverse的部分的最后一个结点,q指向即将reverse的下一个结点
22         for (int i = m; i < n; ++i) {
23             t->next = q->next;
24             q->next = p->next;
25             p->next = q;
26             q = t->next;
27         }
28         return dummy.next;
29     }
30 };
View Code

一定要画图分析,小心指针操作。