Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
public class Solution {
public ListNode reverse(ListNode head){
ListNode p = head;
ListNode pre = new ListNode(0);
head = pre;
while(p != null){
ListNode r = p.next;
p.next = head.next;
head.next = p;
p = r;
}
pre = pre.next;
head.next = null;
return pre;
}
public ListNode reverseKGroup(ListNode head, int k) {//k个元素判断一次
ListNode p1 = head;
if(k<=1 || head == null) return head;
int count = 0;
ListNode pre = null;
while(p1 != null && count < k){
count++;
pre = p1;
p1 = p1.next;
}
if(count < k) return head;
pre.next = null;
pre = reverse(head);//head转置后变为新链表的最后一个节点,返回新链表的头结点
head.next = reverseKGroup(p1, k);
return pre;
}
}