使用递归
在进行K个节点翻转的时候需要设置变量来存储游标,当前节点和父节点。
采用在翻转操作结束后进行长度的检查,牺牲了最后一组不足k个的节点对两次翻转的时间,但是省去了每次递归先进行长度计算,较为效率。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||head.next==null||k==1)return head;
ListNode res = head;
ListNode parent = head,current = null;
int count = 1;
head = head.next;
while(head!=null&&count<k){
current = head;
head = head.next;
current.next = parent;
parent = current;
count ++ ;
}
if(count<k){
ListNode tmp = current.next;
current.next = null;
for(int i=0;i<count-1;i++){
current = tmp;
tmp = tmp.next;
current.next = parent;
parent = current;
}
return current;
}
res.next = reverseKGroup(head, k);
res = current;
return res;
}
}
网友评论