public class K {
public Node reverseKGroup(Node head, int k) {
Node node = new Node();
node.next = head;
Node pre = node;
Node end = node;
while(end != null){
for(int i = 0;i < k && end != null;i++){
end = end.next;
}
if(end == null){
break;
}
Node start = pre.next;
Node next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = start;
}
return node.next;
}
public Node reverse(Node node){
Node curnode = node;
Node oldnode = null;
Node newnode = null;
while(curnode != null){
oldnode = curnode.next;
curnode.next = newnode;
newnode = curnode;
curnode = oldnode;
}
return newnode;
}
}
链表K个元素进行翻转
最新推荐文章于 2023-02-23 14:21:37 发布