给你一个链表,让你两个两个的将其翻转!
这题其实就是K个一组翻转链表的特例,这里想写一下的目的是,虽然常规做法也是递归,那么我可不可以完全使用递归的方式做一下
方法一:常规做法,先翻转K个链表,再递归
public static ListNode func2(ListNode head){
if (head==null ||head.next==null) return head;
ListNode tail = head;
for (int i=1;i<=2;i++){
if (tail==null){
return head;
}
tail=tail.next;
}
//此时的tail就是下一个要翻转的头结点
ListNode reverse = reverse(head,tail);
head.next = func2(tail);
return reverse;
}
//翻转链表
public static ListNode reverse(ListNode head,ListNode tail){
if (head==tail ||head.next==tail) return head;
ListNode newhead = reverse(head.next,tail);
head.next.next = head;
head.next = null;
return newhead;
}
方法二:因为是两个一组翻转链表,我直接翻转,再递归
//递归
public static ListNode func1(ListNode head){
if (head==null ||head.next==null) return head;
ListNode newhead= head.next;//返回头结点的下一个节点
ListNode node = head.next.next;
head.next.next = head;
head.next = func1(node);
return newhead;
}