2m,Java O(n) code


  • 0
    N

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      private class Result{
      public ListNode newHead;
      public ListNode newTail;
      public ListNode oldHead;
      Result(ListNode h, ListNode t, ListNode o){
      newHead = h;
      newTail = t;
      oldHead =o;
      }
      }
      private boolean hasKLength(ListNode head ,int k){
      ListNode follow = head;
      int len = 0;
      while(follow !=null){
      follow = follow.next;
      len++;
      }
      if(k>len){
      return false;
      }
      return true;
      }
      private Result reverseKElement(ListNode head, int k){
      ListNode oldHead = head;
      ListNode newHead = null;
      ListNode newHeadTail = head;
      for(int i =0; i<k; i++){
      ListNode temp = oldHead;
      oldHead = oldHead.next;
      temp.next = newHead;
      newHead =temp;
      }

      // newHeadTail.next = oldHead;
       return new Result(newHead, newHeadTail, oldHead);
      

      }
      public ListNode reverseKGroup(ListNode head, int k) {
      if(k == 0) return head;
      ListNode follow = head;
      Result result = null;
      while(follow != null){
      if(hasKLength(follow, k)){
      Result result2 = reverseKElement(follow, k);
      if(result != null) {
      result.newTail.next = result2.newHead;
      result.newTail = result2.newTail;
      result.oldHead = result2.oldHead;
      }else{
      result = new Result(result2.newHead, result2.newTail, result2.oldHead);
      }
      follow = result2.oldHead;
      }else{
      break;
      }
      }
      if(result == null) return head;
      result.newTail.next = follow;
      return result.newHead;

      }
      }


  • 0
    X

    You should reformat your code by surrounding your code block with 3 backticks ```


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.