最后那个reverse函数写的比较费劲,主要是pre.next 和last.next必须指向正确位置
ref 解释 http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html
ref 代码 http://www.cnblogs.com/springfor/p/3864530.html
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null || k<2) return head;
ListNode dum = new ListNode(-1);
dum.next = head;
ListNode pre = dum, cur = head;
int cnt=0;
while(cur!=null){
cnt++;
ListNode next = cur.next;
if(cnt==k){
pre = reverse(pre, next);
cnt=0;
}
cur = next;
}
return dum.next;
}
public ListNode reverse(ListNode pre, ListNode next){ //pre 1->2->3 next to 1<-2<-3, return 1
ListNode last = pre.next ;
ListNode cur = last.next;
while(cur!=next){
<strong><span style="color:#ff0000;background-color: rgb(255, 255, 204);"> // ListNode tmp = cur.next; 这里是错误的关键,必须要把last指向正确的下一个位置
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
// cur = tmp;
cur = last.next;</span></strong>
}
return last;
}
}