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
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 Public classSolution {Ten PublicListNode Reversekgroup (ListNode head,intk) { One if(Head = =NULL|| Head.next = =NULL|| K <= 1) { A returnhead; - } - theListNode dummy =NewListNode (0); -Dummy.next =head; -Head =dummy; - while(Head! =NULL) { +Head =Reversek (head, k); - } + returnDummy.next; A } at - PrivateListNode Reversek (ListNode head,intk) { -ListNode next =Head.next; - for(inti = 0; I < K; i++) { - if(Next = =NULL) { - return NULL; in } -Next =Next.next; to } + -ListNode node =Head.next; theListNode pre =NULL, Curt =node; * for(inti = 0; I < K; i++) { $ListNode temp =Curt.next;Panax NotoginsengCurt.next =Pre; -Pre =Curt; theCurt =temp; + } AHead.next =Pre; theNode.next =Curt; + returnnode; - } $}
Reverse Nodes in K-group