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

题目链接:https://leetcode.com/problems/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.


思路:借助我非常喜欢的虚拟头结点,让链表走到第一个在需要交换的结点记为post(这个结点将会成为翻转区域的尾结点),并且记录post之前的一个结点记为p。找到这个点之后就可以将在范围之内的结点都插入到p的后面,直到走出需要翻转的区域,让剩下的区域链接到post后面即可。

举个栗子:

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

1.先让p结点走到1,2结点是第一个需要交换的结点记为post,并最终会成为交换范围的尾结点。

2.让3插入到1后面,变为1->3->2    4->5->NULL

3.让4插入到1后面,变为1->4->3->2   5->NULL

4.让剩余的链接到2后面,变为1->4->3->2->5->NULL

时间复杂度为O(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* pHead = new ListNode(0);
        pHead->next = head;
        ListNode* p = pHead, *post;
        int i = 1;
        while(i < m && p)//找到第一个要交换的结点
        {
            p = p->next;
            i++;
        }
        post = p->next;
        ListNode* q = post->next;
        while(q && i < n)//将需要翻转的结点翻转
        {
            ListNode* tem = q->next;
            q->next = p->next;
            p->next = q;
            q = tem;
            i++;
        }
        post->next = q;
        head = pHead->next;
        delete pHead;
        return head;
    }
};



你可能感兴趣的:(LeetCode,链表)