[leedcode 25] Reverse Nodes in k-Group
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, only nodes itself may be 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 class Solution { public ListNode reverseKGroup(ListNode head, int k) { //本题是旋转两个节点的延伸,此题需要旋转k个节点。最重要的是需要画好图,每次 //循环之前确定各个指针的位置。 //本题针对最后一组个数不足k的处理方式是,先要遍历一组,看个数是否满足k个 //然后再开始反转每个小组。如果不满足则直接返回,不需要反转。 //本题需要声明一个新头指针,代表第一个组的前一个组的尾节点。 //本题需要申明一个指针,代表上一个组的最后位置lastGroup,还需要保存新组的头结点(未反转之前) if(head==null||head.next==null) return head; ListNode newHead=new ListNode(-1); boolean isvalid=true; ListNode lastGroup=newHead; ListNode first=head; lastGroup.next=head; ListNode last=lastGroup; ListNode p=head;//注意 while(isvalid){ for(int i=0;i<k;i++){ if(p==null){//注意 isvalid=false; break; } p=p.next; } if(isvalid){ p=lastGroup.next; first=p; last=lastGroup; for(int i=0;i<k;i++){ ListNode pre=p.next; p.next=last; last=p; p=pre; } lastGroup.next=last; first.next=p; lastGroup=first; } } return newHead.next; } }