题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (k == 1) {
            return head;
        }
        int c = 0;
        ListNode aHead = null, aTail = null, next = head, start = head;
        while(next != null) {
            c++;
            if (c == k) {
                ListNode end = start, aNext = end.next, tmp;
                while(start != next) {
                    tmp = aNext.next;
                    aNext.next = start;
                    end.next = tmp;
                    start = aNext;
                    aNext = end.next;
                }
                if (aHead == null) {
                    aHead = start;
                }
                if (aTail != null) {
                    aTail.next = start;
                }
                aTail = end;
                next = start = aNext;
                c = 0;
            } else {
                next = next.next;
            }
        }
        return aHead == null ? head : aHead;
    }
}

全部评论

相关推荐

昨天 17:48
中山大学 C++
点赞 评论 收藏
分享
10-29 15:38
门头沟学院 Java
榕城小榕树:难道你简历里写了配送路径优化算法?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务