LeetCode - M - Reverse Linked List II

題意

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

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

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解法

記錄翻轉部分之前的一個節點pre,其他部分和單純翻轉一樣

實現

/**
 * 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 == NULL || m == n) return head;
        ListNode* pre = NULL;
        ListNode* cur = head;
        int idx = 1;
        while(idx < m && cur != NULL){
            ++idx;
            pre = cur;
            cur = cur->next;
        }
        ListNode* shead = cur;
        while(idx < n && cur->next != NULL){
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = shead;
            shead = next;
            ++idx;
        }
        if(pre == NULL) head = shead;
        else pre->next = shead;
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章