25.K个一组翻转链表
思路:
把链表节点按照k个一组分组,可以使用一个指针head依次指向每组的头节点,这个指针每次向前移动k步,直至链表结尾,对于每个分组, 先判断它的长度是否大于等于k,若是,就翻转这部分链表,否则不需要翻转
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode hair = new ListNode(0);
hair.next = head;
ListNode pre = hair;
while(head != null){
ListNode tail = pre;
//查看剩余部分长度是否大于等于k
for(int i = 0 ;i<k;i++){
tail = tail.next;
if(tail == null){
return hair.next;
}
}
ListNode next = tail.next;
ListNode[] reverse = Reverse(head,tail);
head = reverse[0];
tail = reverse[1];
//把子链表重新接回原链表
pre.next = head;
tail.next = next;
pre = tail;
head = tail.next;
}
return hair.next;
}
//反转链表,返回子链表的头部与尾部
public ListNode[] Reverse(ListNode head,ListNode tail){
ListNode prev = tail.next;
ListNode p = head;
while(prev != tail){
ListNode next = p.next;
p.next = prev;
prev = p;
p = next;
}
return new ListNode[]{tail,head};
}
}