Reverse Linked List II

来源:互联网 发布:轩子巨2兔黑历史知乎 编辑:程序博客网 时间:2024/04/29 18:24

思路:
迭代。不断的交换[m,n]区间首位元素的val,不用管next。
Do it in-place and in one-pass. ——> 即需要空间复杂度O(1),时间复杂度O(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) {        if(head == nullptr) return head;        ListNode *start = head;        for(int i = 1; i < m; ++i) {            start = start->next;        }        for(int i = m; i < n; ++i) {            ListNode *end = start;            for(int j = i; j < n; ++j) {                end = end->next;            }            swap(start->val, end->val);            n--;            start = start->next;        }        return head;    }};
0 0
原创粉丝点击