25. K 个一组翻转链表

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5

当 k = 3 时,应当返回: 3->2->1->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

//之前是用c写的迭代法,好久之前了,现在又做到这题,用递归的方法解决这个问题,找出问题的核心

//1.返回值是什么------>是头节点,是翻转以后每个子链的头节点,找出这个头节点返回

//2.每个子链在做什么,也就是递归的每一层在干什么,是要翻转这条子链

//3.递归到底的结束条件是什么,是count==0,

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k==1)
            return head;
        ListNode p=head;
        int sum=0;
        while(p!=null)      //找出一共有多少个节点,计算出需要我们去翻转几条子链,也就是将链表去分割
        {
            sum+=1;
            p=p.next;
        }
        int count=sum/k;
        return reverse(head,count,k);
        
    }
    public ListNode reverse(ListNode head,int count,int k)
    {
        if(count==0)
            return head;
        ListNode pre=head;
        ListNode cur=head.next;
        ListNode next=cur.next;
        for(int i=0;i<k-1;i++)
        {
            cur.next=pre;
            pre=cur;
            cur=next;
            if(next!=null)
                next=next.next;
        }
        head.next=reverse(cur,--count,k);    //这里要注意一点,这个count要减去1,不能用count--,这样的话,count是减1了,但是递归下去的变量并没有减1,还是原来的值
        return pre;
    }
}

猜你喜欢

转载自www.cnblogs.com/cold-windy/p/11366097.html