给一个单向链表以及整数N,使得每N个元素为一组进行翻转。要求时间复杂度O(n), 空间复杂度O(1)。
public class Solution {
/**
* reverse the given linked list
* @param head ListNode类 the head of the linked list
* @param n int整型 the N
* @return ListNode类
*/
public ListNode reverseLinkedList (ListNode head, int n) {
if(head == null) return null;
ListNode a = head;
ListNode b = head;
for(int i = 0; i < n; i++){
if(b == null) break;
b = b.next;
}
ListNode newHead = newReverse(a,b);
a.next = reverseLinkedList(b,n);
return newHead;
}
//可以参考LeetCOde反转链表,多一个条件:当前节点不为尾节点b
public ListNode newReverse(ListNode a, ListNode b){
ListNode pre = null;
ListNode cur = a;
while(cur != null && cur != b){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}