您的位置:首页 > 其它

[Leetcode] 92. Reverse Linked List II 解题报告

2017-04-19 09:17 399 查看
题目

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.
思路

这道题目的思路不难,需要注意的是in-place和one-pass的要求。假设需要翻转m到n之间的元素,那么我们首先定位到m位置,然后遍历并且依次翻转,直到到达n位置。最后把m位置的元素和n之后的元素连接起来即可。为了处理方便,仍然引入虚拟头结点。

代码

/**
 * 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 || n - m <= 0) {
            return head;
        }
        ListNode pre_head(0);
        pre_head.next = head;
        ListNode* p = &pre_head;
        ListNode* post;
        int i = 1;
        while(i < m && p) {                 // come to position m
            p = p->next;
            i++;
        }
        post = p->next;
        ListNode* q = post->next;
        while(q && i < n) {                 // traverse until position n
            ListNode* temp = q->next;
            q->next = p->next;
            p->next = q;
            q = temp;
            i++;
        }
        post->next = q;
        return pre_head
4000
.next;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: