Reverse Nodes in K-group
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, and only nodes itself is 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
Problem Solving Ideas:
This spent maths the time of my afternoon, must wall detention ~
In fact, this problem contains a small problem, is the single-linked list reversal problem, the idea is to first scan the node in the back, the time complexity of only O (n), the space Complexity of O (1). Based on this idea, we make a slight change, that is, the solution to the problem.
/** * 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) {if (head==null| | K<=1) {return head; } listnode* myhead=new ListNode (0); myhead->next=head; listnode* Last=myhead; listnode* Pre=myhead; while (true) {int i=0; while (i<k&&last!=null) {last=last->next; i++; } if (i<k| | Last==null) {break; } listnode* parthead=pre->next; Pre->next=reverse (Parthead, last); Pre=last=parthead; } head=myhead->next; Delete Myhead; return head; }//Enter the head node of the linked list, and the last node of the linked list, and return the header nodes of the linked list after reversal listnode* reverse (listnode* Head, listnode*) {if (head==l AST) { return head; } listnode* current=head->next; The current node of the original linked list listnode* newhead=head; The head node of the new linked list newhead->next=last->next; while (current!=last) {listnode* temp=current->next; current->next=newhead; Newhead=current; Current=temp; } current->next=newhead; Newhead=current; return newhead; }};
[Leetcode] Reverse Nodes in K-group