第一重-简单反转链表
递归实现
递归终止条件是head到最后一个
class Solution{
pubilc ListNode reverseListNode(ListNode head){
if(head==null||head.next==null) return head;
ListNode newHead = reverseListNode(head.next);
head.next.next=head;
head=null;
return newHead;
}
}
迭代实现:
第二重-反转前k个链表
使用successor记住第k+1个位置,递归结束head要指向successor
递归终止条件是来到第k个位置,每一次递归的过程相当于从head.next开始,反转k-1个链表
class Solution{
ListNode successor = null;
ListNode reverseN (ListNode head,k){
if(k == 1){
successor = head.next;
return head;
}
ListNode newHead = reverseN(head.next,k-1);
head.next.next=head;
head.next=successor;
return newHead;
}
}
第三重-反转(m,n)部分链表
head先到达m-1的位置
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==1){
return reverseN(head,n);
}
head.next=reverseBetween(head.next,m-1,n-1);
return head;
}
ListNode successor = null;
public ListNode reverseN(ListNode head, int k ) {
if(k==1){
successor=head.next;
return head;
}
ListNode newHead = reverseN(head.next,k-1);
head.next.next=head;
head.next=successor;
return newHead;
}
}
第四重-k个一组反转
利用反转1-k。再循环实现1-k,2k+1-3k
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null||head.next==null){
return head;
}
ListNode tail=head;
for(int i=0;i<k;i++){
if(tail==null){
return head;
}
tail=tail.next;
}
ListNode newHead=reverse(head,tail,k);
head.next=reverseKGroup(tail,k);
return newHead;
}
public ListNode reverse(ListNode head,ListNode tail,int k){
if(k==1) return head;
ListNode newHead=reverse(head.next,tail,k-1);
head.next.next=head;
head=null;
return newHead;
}
}
假如最后不满足k个也反转:
要求从后往前输出
参考了labuladong,并增加了一点内容