leetcode系列(41)Reverse Nodes in K-Group

来源:互联网 发布:加强网络舆情管理 编辑:程序博客网 时间:2024/06/04 19:35

Given a linked list, reverse the nodes of alinked list k at a time and return its modified list.If thenumber of nodes is not a multiple of k then left-out nodes inthe end should remain as it is.You may not alter the values in the nodes, onlynodes itself may be changed.Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you shouldreturn: 2->1->4->3->5

For k = 3, you shouldreturn: 3->2->1->4->5

解答:这个题目就是考察链表操作过程中细心的程度,还有一个翻转链表的辅助函数(稍微有些变动,末尾节点不一定是nullptr),用dummy_node辅助减少代码难度。

class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if (k <= 1) {            return head;        }        auto dummy = ListNode(0);        dummy.next = head;        auto start = head;        auto ptr = &dummy;        while (start != nullptr) {            auto end = start;            for (int i = 1; i < k; i++) {                end = end->next;                if (end == nullptr) {                    return dummy.next;                }            }            ptr->next = _reverse(start, end->next);            ptr = start;            start = start->next;        }        return dummy.next;    }private:    // reverse nodes [start, end]    ListNode* _reverse(ListNode* start, ListNode* end) {        ListNode* pre = nullptr;        auto cur = start;        while (cur != end) {            auto nxt = cur->next;            cur->next = pre;            pre = cur;            cur = nxt;        }        start->next = cur;        return pre;    }};


0 0