My code runs ok in Eclipse but not here, why?


  • 0
    M

    My code runs ok in Eclipse for the same input ({1, 2, 3, 4}) than here, but here returns head and Eclipse returns {1, 4, 2, 3}, the correct answer. Why does it fail here?

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
    	public ListNode reorderList(ListNode head) {
    
    		if (head == null) {
    			return null;
    		}
    
    		if (head.next == null || head.next.next == null) {
    			return head;
    		}
    
    		final int LENGTH = length(head);
    
    		ListNode aux = head;
    		
    		if (LENGTH == 3) {
    			aux = aux.next;
    			head.next = aux.next;
    			head.next.next = aux;
    			aux.next = null;
    			return head;
    		}
    
    		ListNode auxAnt;
    
    		int leftStop = LENGTH / 2;
    		
    		ListNode fstMidList = new ListNode(aux.val);		
    		auxAnt = fstMidList;
    		for (int i = 1; i < leftStop; i++) {
    			aux = aux.next;
    			auxAnt.next = new ListNode(aux.val);
    			auxAnt = auxAnt.next;
    		}
    		if (LENGTH % 2 != 0) {
    			aux = aux.next;
    			auxAnt.next = new ListNode(aux.val);
    			auxAnt = auxAnt.next;
    			leftStop++;
    		}
    
    		aux = aux.next;
    		ListNode sndMidList = new ListNode(aux.val);
    		for (int i = leftStop + 1; i < LENGTH; i++) {
    			aux = aux.next;
    			auxAnt = new ListNode(aux.val);
    			auxAnt.next = sndMidList;
    			sndMidList = auxAnt;
    		}
    		
    		ListNode list = fstMidList;
    		fstMidList = fstMidList.next;
    		aux = list;
    		while (fstMidList != null || sndMidList != null) {
    
    			if (aux != null && sndMidList != null) {
    				aux.next = sndMidList;
    				sndMidList = sndMidList.next;
    				aux = aux.next;
    			}
    
    			if (aux != null && fstMidList != null) {
    				aux.next = fstMidList;
    				fstMidList = fstMidList.next;
    				aux = aux.next;
    			}
    		}
    		
    		return list;
    	}
    
    	private int length(ListNode head) {
    		int length = 1;
    
    		ListNode aux = head;
    		while (aux.next != null) {
    			length++;
    			aux = aux.next;
    		}
    
    		return length;
    	}
    
    }

Log in to reply
 

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