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 * head0; int flag; listnode * reversekgroup (listnode * head, int K) {If (k <2) return head; listnode * H = reverse (Head, k); If (flag = 0) return head; listnode * tail = head; while (head0! = NULL & flag = 1) {listnode * TMP = head0; tail-> next = reverse (head0, k); tail = TMP;} return h;} PRIVATE: listnode * reverse (listnode * head, int N) {listnode * P = head; int num = N; while (Num> 0 & P! = NULL) {P = p-> next; num --;} If (P = NULL & num> 0) {flag = 0; // flag = 0 indicates that return head is not flipped;} flag = 1; // flag = 1 indicates that listnode * P1 = head is flipped, * P2 = p1-> next, * P3; while (n-1) {P3 = P2-> next; P2-> next = p1; P1 = P2; P2 = P3; n --;} head-> next = NULL; head0 = P2; return P1 ;}};
[Leetcode] Reverse nodes in K-group