[leetcode]25. Reverse Nodes in k-Group

来源:互联网 发布:网络信息安全现状 编辑:程序博客网 时间:2024/06/03 19:02

题目链接:https://leetcode.com/problems/reverse-nodes-in-k-group/description/


Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

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

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

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


class Solution{public:    ListNode* reverse(ListNode* first, ListNode* last)    {        ListNode* new_head = new ListNode(-1);        ListNode*p=first;        while ( p != last )        {            ListNode*t=p;            p=p->next;            t->next=new_head->next;            new_head->next=t;        }        return new_head->next;    }    ListNode* reverseKGroup(ListNode* head, int k)    {        auto node=head;        for (int i=0; i < k; ++i)        {            if ( ! node  )                return head; // nothing to do list too sort            node = node->next;        }        auto new_head = reverse( head, node);        head->next = reverseKGroup( node, k);        return new_head;    }};


原创粉丝点击