题解 | #链表中的节点每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) { if(head == null){ return null; } ListNode temp = head; return dfs(temp,k); } ListNode dfs(ListNode root,int k){ if(root == null){ return null; } ListNode prev = null; ListNode cur = root; ListNode next = root; ListNode temp = root; int count = k; while(temp != null && count > 0){ temp = temp.next; count--; } if(count > 0){ return root; } ListNode h = temp; int a = k; while(next != null && a > 0){ next = cur.next; cur.next = prev; prev = cur; cur = next; a--; } root.next = dfs(h,k); return prev; } }

全部评论

相关推荐

牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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