leetcode 92 Reverse Linked List II

/**
 * 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(m==n) return head;
        int num=1;
        ListNode ln(0);ln.next=head;
        ListNode* pre=&ln,*cur=head;
        while(num<m&&cur) {
            pre=cur;
            cur=cur->next;
            ++num;
        }
        ListNode* npre=pre,*ncur=cur;
        while(num<=n&&cur) {
            ListNode* tmp=cur->next;
            cur->next=pre;
            pre=cur;
            cur=tmp;
            ++num;
        }
        npre->next=pre;
        ncur->next=cur;
        return ln.next;
    }
};

 

posted @ 2020-04-07 10:42  qiujiejie  阅读(78)  评论(0编辑  收藏  举报