Anybody who can help me out?!!?


  • 0
    A

    I think I am right in a right logic on this problem, and I do sure there is some minor problem in this code. But I cannot find it! Somebody please help me. A lot of people on leetcode with this problem adopted just almost same method as mine, I believe everyone can read to know what I mean by that.

    public class Solution {
        public void reorderList(ListNode head){
    		ListNode fast = head,slow = head,pre = null;
    		
    		while(fast != null && fast.next != null)
    		{
    			fast = fast.next.next;
    			slow = slow.next;
    		}
    		
    		if(fast != null){
    			slow = slow.next;
    		}
    		
    		fast = head;
    		
    		ListNode next = slow.next;
    		slow.next = null;
    		while(next != null)
    		{	
    			pre = slow;
    			slow = next;
    			next = next.next;
    			slow.next = pre;
    		}
    		
    		ListNode iter = head;
    		while(iter.next != null)
    			iter = iter.next;
    		
     		iter.next = slow;
    		
    		ListNode fastnext = fast.next;
    		ListNode slownext = slow.next;
    		while(slownext != null)
    		{
    			fast.next = slow;
    			fast = fastnext;
    			fastnext = fastnext.next;
    			slow.next = fast;
    			slow = slownext;
    			slownext = slownext.next;
    		}
    	}
    }

  • 0
    H

    hi.here are my modified version.it can AC.

    public class Solution {
    public void reorderList(ListNode head){
        if(head==null||head.next==null) return;      //add,
        ListNode fast = head,slow = head,pre = null;
    
        while(fast != null && fast.next != null)
        {
            fast = fast.next.next;
            slow = slow.next;
        }
        ////delelte ,if not some case like [1,2,3] will be fail.
        // if(fast != null){
        //     slow = slow.next;
        // }
    
        fast = head;
    
        ListNode next = slow.next;
        slow.next = null;
        while(next != null)
        {   
            pre = slow;
            slow = next;
            next = next.next;
            slow.next = pre;
        }
        ////delelte, if not there will be TLE.two halves need to be separated!
        // ListNode iter = head;
        // while(iter.next != null)
        //     iter = iter.next;
    
        // iter.next = slow;
    
        ListNode fastnext = fast.next;
        ListNode slownext = slow.next;
        while(slownext != null)
        {
            fast.next = slow;
            fast = fastnext;
            fastnext = fastnext.next;
            slow.next = fast;
            slow = slownext;
            slownext = slownext.next;
        }
    }
    

    }


Log in to reply
 

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