微软: Reverse Linked List II

Posted hisonsandiego

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微软: Reverse Linked List II相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Jan 23 - Reverse Linked List; Linked List; Pointers;

206. Reverse Linked List

206. Reverse Linked List

链表-Reverse Linked List

206. Reverse Linked List

Reverse Linked List