您的位置:首页 > 其它

92. Reverse Linked List II

2018-01-26 16:04 232 查看
class Solution {

public:

    ListNode* reverseBetween(ListNode* head, int m, int n) {

        if(head==NULL) return head;

        ListNode* tail = head;

        ListNode* temp=new ListNode(0);

        ListNode* pre;

        ListNode* temp1; 

        temp->next = head;

        pre  = temp;

        int pos = 1;

        ListNode* cursor;

        while(m>pos){

            tail = tail->next;

            temp = temp->next;

            pos++;

        }

        cursor = tail->next;

        while(pos<n&&cursor!=NULL){

            temp1 = temp->next;

            //printList(pre);

            temp->next = cursor;

            cursor=cursor->next;

            tail->next = cursor;

            temp->next->next = temp1;

            pos++;

        }

        return pre->next;

    }

    void printList(ListNode* L1){

        while(L1!=NULL){

            cout<<L1->val;

            L1 = L1->next;

        }

        cout<<endl;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息