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

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

http://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(head ==null || head.next==null) return head;
        ListNode tail = head;
        ListNode begin = tail;
        for(int i=0;i<k;i++){
            if(tail==null) return head;
            tail = tail.next;
        }
        for(int i=0;i<k;i++){
            if(i==k-1){
                begin.next = null;
            }else{
                begin = begin.next;
            }
        }
        ListNode newHead = reverse(head);
        head.next = reverseKGroup(tail,k);
        return newHead;
        
    }
    
    public ListNode reverse(ListNode head){
        ListNode cur = head;
        ListNode pre = null;
        while(cur!=null){
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}
全部评论

相关推荐

牛客44664404...:把个人技能删了搞这么长干什么!还有你面试要先针对那个公司的技术栈专门去准备,别一问三不知,他需要你会他们公司对口的技术,写这么多不对口没有用
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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