题解 | #链表中的节点每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;
    }
}

全部评论

相关推荐

zhiyog:哈哈哈哈哈哈哈哈哈哈哈哈哈
点赞 评论 收藏
分享
八股刚起步,看了javaguide,小林coding,还有面渣,感觉面渣是体验最好的,请问只看面渣够用吗,有不完善的需要补吗?
码农索隆:先背最基础的知识,然后理解情景题,现在面试大多数喜欢问情景题,更考验面试者的基础和临场发挥情况
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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