题解 | #链表中的节点每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){
              return null;
          }
          ListNode tmp = head;
          for (int i = 0; i < k; i++) {
              if (tmp == null){
                  return head;
              }
              tmp = tmp.next;
          }
          ListNode newHead = reverse(head, tmp);
          head.next = reverseKGroup(tmp, k);
          return newHead;
      }
      public static ListNode reverse(ListNode head, ListNode tail){
          ListNode pre = null;
          ListNode next = null;
          while (head != tail){
              next = head.next;
              head.next = pre;
              pre = head;
              head = next;
          }
          return pre;
      }
  }
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务