Iterative Solution


  • 0
    D

    '''
    public ListNode reverseKGroup(ListNode head, int k) {
    if(k<=1 || head==null || head.next==null) return head;
    ListNode root=head;
    Stack<ListNode> stk=new Stack<ListNode>();
    ListNode dummy=new ListNode(0);
    ListNode result=dummy;
    int i=0;
    while(root!=null){
    i++;
    stk.add(root);
    root=root.next;
    if(i==k){
    i=0;
    while(!stk.isEmpty()){
    result.next=stk.pop();
    result=result.next;
    }
    }
    }
    Stack<ListNode> tmp=new Stack<ListNode>();
    while(!stk.isEmpty() && dummy.next!=null){
    tmp.add(stk.pop());
    }
    while(!tmp.isEmpty()){
    result.next=tmp.pop();
    result=result.next;
    }
    result.next=null;
    if(dummy.next==null) return head;
    return dummy.next;
    }
    '''


Log in to reply
 

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