What is wrong with my code


  • 0
    J

    I am trying to use to stack to add the nodes to be reversed. And then pop it and link the pointers before m and after n.

    public class Solution {
          public ListNode reverseBetween(ListNode head, int m, int n) {
        
        if(head==null) return head;
        ListNode current= head;
        int i=0;
        Stack<ListNode> reverse = new Stack<>();
        while(i<m-1)
        {
            if(current.next==null) return head;
            current=current.next;
            i++;
        }
        ListNode temp= current;
        while(i<n)
        {
            if(temp==null)return head;
            reverse.push(temp);
            temp=temp.next;
            i++;
        }
        System.out.println(temp.val);
        while(!reverse.empty())
        {
            //System.out.println(current.next.val);
            ListNode t=reverse.pop();
            //System.out.println(t.val);
            current.next=t;
            current=current.next; 
            
        }
        current.next=temp;
        
        return head;
    }
    

    }


  • 0
    D

    Based on the example in the question it looks to me like you head into the last while loop with current = 2node and reverse = {2, 3, 4} then you do 2node.next = 4node.

    The final result should be 1-4-3-2-5 so in that case you would want 1node.next = 4node. You need to somehow keep track of the node before the part that you have to reverse if it is not in the reversal part of the list.


Log in to reply
 

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