[LC 25.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) {
        if (head == null)
            return null;
        //反转(a,b)区间的k个数
        ListNode a,b;
        a = b = head;
        for (int i=0;i<k;i++){
            if(b == null)
                return head;
            b = b.next;
        }
        ListNode newHead = reverse(a,b);
        a.next = reverseKGroup(b,k);
        return newHead;
    }

    public ListNode reverse(ListNode a,ListNode b){
        ListNode pre,cur,nxt;
        pre = null;
        cur = nxt = a;
        while (cur != b){
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}
全部评论

相关推荐

02-04 15:03
南昌大学 Java
想去三亚看海的迪恩在...:刚刚打电话了说不录取,收了学信网和身份证,入职的信息条都发给我了,这种不录取究竟何意味?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务