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
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode Reversekgroup (ListNode head,intk) {if(Head = =NULL|| Head.next = =NULL|| K = = 1) returnHead; ListNode Dummy=NewListNode (0); Dummy.next=Head; ListNode Pre=dummy; intLen = 0; while(Head! =NULL) {len++; if(len% k = = 0) {Pre=reverselist (pre, head.next); Head=Pre.next; } ElseHead=Head.next; } returnDummy.next; } PublicListNode reverselist (listnode L1, ListNode next) {if(L1 = =NULL|| L1.next = =NULL) returnL1; ListNode Slow=L1.next; ListNode Fast=Slow.next; while(Fast! =next) {Slow.next=Fast.next; Fast.next=L1.next; L1.next=Fast; Fast=Slow.next; } returnslow; }}
Reverse Nodes in K-group