/**
* 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) {
if(head==null || head.next==null) return head;
ListNode tail=head;
//tail指的是1->2->3 3为这个tail
for(int i=0;i<k;i++){
if(tail==null) return head;
tail=tail.next;
}
ListNode newHead=reverse206(head,tail); //[) 如果(1,4) 1->2->3->4 翻转1->2->3 这是newHaed为3
head.next=reverseKGroup(tail,k); //head.next=1 3->2->1 第3位(K-1位)
return newHead;
}
public ListNode reverse206(ListNode currhead,ListNode tail){
ListNode pre=null;
//1->2->3
while(currhead!=tail){
ListNode next=currhead.next; //2
currhead.next=pre;
pre=currhead;
currhead=next; //?
}
return pre;
}
}
25. K 个一组翻转链表
最新推荐文章于 2024-07-13 18:57:33 发布