码迷,mamicode.com
首页 > 其他好文 > 详细

微软: Reverse Linked List II

时间:2018-01-20 16:23:40      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:linked   break   create   blog   int   nod   str   lis   head   

key point

no special data structure, only operation trick listed as below.

create a new node as a vritual head which will convinient for the operation.

change te node one bye one from m to 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) {
        //check the input 
        if ( head == nullptr) return nullptr;
        if (head->next == nullptr) return head;
        
        ListNode* headnode = new ListNode(0);
        headnode -> next = head;
        
        int i = 1;
        ListNode* first = headnode;
        ListNode* next = headnode;
        ListNode* cur = headnode;
        
        while (i < m){//next node should be reversed that is m
            first = first ->next;
            i++;
        }
        
        ListNode* temp = first->next;
        next = first->next->next;
        i+=1;
        
        while (i <=n){
            if (next == nullptr) break;
            cur = next;
            next = next->next;
            cur->next = first->next;
            first->next = cur;
            i++;
        }
        
        temp->next = next;
        head = headnode->next;
        delete headnode ;
        return head;
    }
};

 

微软: Reverse Linked List II

标签:linked   break   create   blog   int   nod   str   lis   head   

原文地址:https://www.cnblogs.com/HisonSanDiego/p/8320752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!