Is it the right way to solve the problem?


  • 0
    S

    The code can work. But I do not know whether I do it in a right way

    public ListNode reverseBetween(ListNode head, int m, int n) {
            java.util.Stack<ListNode> stack = new java.util.Stack<ListNode>();
            ListNode beforeM = null;
            ListNode afterN = null;
            ListNode node = new ListNode(0);
            node.next = head;
            ListNode newHead = node;
            int count = 0;
            do{
                if(count == (m - 1)){
                	beforeM = node;
                }else if(count >= m && count <=n){
                	stack.push(node);
                }else if(count == n + 1){
                	afterN = node;
                }
                count ++;
            }while((node = node.next) != null);
            
            while(stack.size() > 0){
            	beforeM.next = stack.pop();
            	beforeM = beforeM.next;
            }
            beforeM.next = afterN;
            return newHead.next;
    }

  • 1
    C

    Although your code can work, but the problem asks us "Do it in-place and in one-pass".
    In your code, java.util.Stack<ListNode> stack = new java.util.Stack<ListNode>(); will use "o(n)" space.


Log in to reply
 

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