Given a linked list, reverse the nodes of a linked listKAt a time and return its modified list.
If the number of nodes is not a multipleKThen left-out nodes in the end shoshould 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
ForK= 2, you shoshould return:2->1->4->3->5
ForK= 3, you shoshould return:3->2->1->4->5
/*** 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 <= 0) return head; listnode * pcount = head; listnode * pter = head; listnode ** Prev = & head; listnode * pnext = NULL; while (pcount! = NULL) {int COUNT = 0; For (; count <K & pcount! = NULL; ++ count) {// judge if K pcount = pcount-> next;} If (COUNT = k) {listnode * pnext = NULL; listnode * pend = pter; listnode * pstart = pter; while (pter! = Pcount) {pnext = pter-> next; pter-> next = pend; pend = pter; pter = pnext;} * Prev = pend; prev = & (pstart-> next); pstart-> next = pter ;}} return head ;}};
[Leetcode] Reverse nodes in K-group