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
There is a similar meaning to the paired conversion of the linked list. Here are two main considerations:
1) invocation and operation of a linked list logical transformation
2) do not have a hover pointer and break link
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {public:void reverse (ListNode * first,listnode * end)//put k elements in inverse {ListNode * p1 = first; ListNode * P2;while (p1! = end&&p1!=null)//Avoid floating pointer, that is, do not operate on null pointer {p2 = p1->next; P1->next = end->next; End->next = p1; P1 = p2; }//the last first pointer is at the end, pointing to the maybe list} listnode *reversekgroup (ListNode *head, int k) {if (head = = NULL | | k<2) r Eturn Head; ListNode * first = head; ListNode * end = first->next; ListNode * pre = NULL; int i = 0; while (I<k-2&&end!=null)//end to point to the K-node {end = end->next; i++; } while (NULL! = end) {if (first = = head)//only once head = end; else Pre->next = end; Reverse (first,end);p re = first; First = first->next;if (first = = NULL) Break;end = first->next; i = 0; while (i<k-2&&end!=null) {end = end->next; i++; }} return head; }};
Daily algorithm 23: Reverse Nodes in K-group