题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
function ListNode(x){
this.val = x;
this.next = null;
function reverseKGroup( head , k ) {
// write code here
var dummy=new ListNode(-1);
dummy.next=head;
var cur=dummy;
while(cur){
var first=cur.next;
var end=cur;
for(var i=0;i<k&&end!=null;i++){
end=end.next;
}
if(!end) break;
var p1=first;
var p2=first.next;
while(p1!=end){
var new_p2=p2.next;
p2.next=p1;
p1=p2;
p2=new_p2;
}
first.next=p2;
cur.next=end;
cur=first;
}
return dummy.next;
}
this.val = x;
this.next = null;
}
// write code here
var dummy=new ListNode(-1);
dummy.next=head;
var cur=dummy;
while(cur){
var first=cur.next;
var end=cur;
for(var i=0;i<k&&end!=null;i++){
end=end.next;
}
if(!end) break;
var p1=first;
var p2=first.next;
while(p1!=end){
var new_p2=p2.next;
p2.next=p1;
p1=p2;
p2=new_p2;
}
first.next=p2;
cur.next=end;
cur=first;
}
return dummy.next;
}