Simple and Modular Java code


  • 0
    C
    public ListNode reorderList(ListNode a) {
    	    if(a==null||a.next == null)
    	        return a;
    	    ListNode mid = getMid(a);
    	    ListNode r = reverse(mid.next);
    	    mid.next = null; //split list into two halves
    	    return mergeAlternate (a,r);
    	}
    	private ListNode mergeAlternate(ListNode a, ListNode r){
    	    ListNode trav1 = a;
    	    ListNode trav2 = r;
    	    while(trav1.next!=null){
    	        ListNode t1 = trav1.next;
    	        ListNode t2 = trav2.next;
    	        trav1.next = trav2;
    	        trav2.next = t1;
    	        trav1 = t1;
    	        trav2 = t2;
    	    }	    
    	    trav1.next = trav2;
    	    return a;
    	}
    	private ListNode reverse(ListNode r){
    	    ListNode p,c,t;
    	    p = null; c = null ; t = r;
    	    while(t!=null){
    	        p =c;
    	        c = t;
    	        t = t.next;
    	        c.next = p;
    	    }
            return c;
    	}
    	private ListNode getMid(ListNode a){
    	    ListNode f = a;
    	    ListNode s = a;
    	    while(f.next!=null&&f.next.next!=null){
    	        f = f.next.next;
    	        s = s.next;
    	    }
    	    return s;
    	}
    

Log in to reply
 

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