leetcode
https://leetcode.cn/problems/reverse-nodes-in-k-group/
解题思路
递归到最后面一段,从最后面开始翻转,每次返回翻转后的头节点。
/** * 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 now=null; now=head; int cnt=0; while(now!=null && cnt<k-1){//如果不到k,直接返回 now=now.next; cnt+=1; } if(now==null){ return head; } ListNode pre=reverseKGroup(now.next,k),next=now.next;//从最后面开始翻转 while(cnt>=0){ ListNode temp=head.next; head.next=pre; pre=head; head=temp; cnt-=1; } return now;//返回每段翻转后的头节点 } }
LeetCode 25. K 个一组翻转链表
2024-07-11 12:52:01 56 阅读