# LeetCode 25 Reverse Nodes in k-Group (Reverse node in K-Group Linked List)

Source: Internet
Author: User

LeetCode 25 Reverse Nodes in k-Group (Reverse node in K-Group Linked List)
Original

``Given a linked list, the node of the linked list is reversed within a certain period of time, and the modified linked list is returned. If the number of knots is not a multiple of K, the remaining nodes remain unchanged. You should not modify the value of a node. Only the node itself can be modified. Only constant space is allowed. For example, for a given 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``
Translation
``Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return: 3->2->1->4->5``
Code

The following code is not mine. Although I think it is almost the same, it is almost the result difference ......

A long way to go!

``/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        auto node = head;        for(int i = 0; i < k; ++ i) {            if(!node) return head;            node = node->next;        }        auto new_head = reverse(head, node);        head->next = reverseKGroup(node, k);        return new_head;            }    ListNode* reverse(ListNode* start, ListNode* end) {        ListNode* head = end;        while(start != end) {            auto temp = start->next;            start->next = head;            head = start;            start = temp;        }        return head;    }};``

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.