第一种:循环o(1)的时间复杂度
public ListNode reverseKGroup (ListNode head, int k) {
if(head==null||head.next==null) return head;
int cnt=0;
ListNode h=head;
ListNode pre=new ListNode(0);
ListNode p=pre;
// write code here
while (head!=null){
ListNode temp=head.next;
cnt++;
//每k个节点的时候 就翻转
if(cnt%k==0){
reverse(h,head,pre);
pre=h;
pre.next=temp;
h=temp;
}
head=temp;
}
if(cnt<k) return h;//不足k个的时候直接返回头节点
return p.next;
}
private void reverse(ListNode h, ListNode head,ListNode pre) {
ListNode s=h;
while (s!=head){
ListNode temp=s.next;
s.next=pre.next;
pre.next=s;
s=temp;
}
head.next=pre.next;
pre.next=head;
}第二种:递归写法
public ListNode reverseKGroup (ListNode head, int k) {
if(head==null||head.next==null) return head;
// write code here
//在不足k的时候
int res = 0;
ListNode h=head;
while(head!=null){
head=head.next;
res++;
}
if(res<k) return h;
//将当前前k个节点一组翻转
ListNode pre=new ListNode(0);
pre.next=null;
int p=0;
ListNode s=new ListNode(0);
ListNode j=h;
while(h!=null){
p++;
ListNode temp=h.next;
h.next=pre.next;
pre.next=h;
if(p==k){
s=temp;
break;
}
h=temp;
}
//System.out.println(s.val);
//将当前第k+1个节点进行递归
ListNode sec=reverseKGroup(s,k);
j.next=sec;
return pre.next;
}
京公网安备 11010502036488号