reverse-linked-list-ii

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

For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,

return1->4->3->2->5->NULL.

Note: 
Given mn satisfy the following condition:

1 ≤ m ≤ n ≤ length of list.

首先找出翻转开始的点,主要喜欢出错的地方就是找到开始的点之后如何一步一步翻转。

每次循环翻转一次,有点不太好表达,忘记的时候来看看代码。

/**
 * 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 || m<1 || n<1 || m>n) return nullptr;
        ListNode temp(-1);
        temp.next=head;
        ListNode *dummy=&temp,*cur=dummy,*start=dummy;
        for(int i=0;i<m;i++)
        {
            if(!cur)
                return nullptr;
            start=cur;
            cur=cur->next;
        }
        for(int i=0;i<n-m;i++)
        {
            ListNode *t=cur->next;
            cur->next=t->next;
            t->next=start->next;
            start->next=t;
        }
        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/jifeng7288/article/details/80337363