Easy and Simple Java Solution


  • 0
    C
    public static ListNode<Integer> ReverseNodesInKGroup(ListNode<Integer> head, int k) {
    		ListNode<Integer> pre = null;
    		ListNode<Integer> p = head;
    		ListNode<Integer> next = breakGroup(p, k);
    		ListNode<Integer> newHead = null;
    		while (next != null) {
    			if(newHead == null)
    				newHead = reverseList(p);
    			else
    				pre.next = reverseList(p);
    			pre = p;
    			p.next = next;
    			p = next;
    			next = breakGroup(p, k);
    		}
    		
    		return newHead;
    	}
    
    	public static ListNode<Integer> breakGroup(ListNode<Integer> head, int k) {
    		int count = 1;
    		ListNode<Integer> p = head;
    		while (p != null && count < k) {
    			p = p.next;
    			count++;
    		}
    		if (p == null)
    			return null;
    		ListNode<Integer> next = p.next;
    		p.next = null;
    		return next;
    	}
    
    	public static ListNode<Integer> reverseList(ListNode<Integer> head) {
    		ListNode<Integer> pre = head;
    		ListNode<Integer> p = head.next;
    		pre.next = null;
    		while(p != null) {
    			ListNode<Integer> next = p.next;
    			p.next = pre;
    			pre = p;
    			p = next;
    		}
    		return pre;
    	}
    

Log in to reply
 

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