C# accepted solution - split, reverse and merge


  • 0
    R
    public void ReorderList(ListNode head) {
            if(head==null || head.next == null || head.next.next == null) return;
    
    		ListNode s = head, f = head;
    		while (f != null && f.next != null)
    		{
    			s = s.next;
    			f = f.next.next;
    		}
    		ListNode h1 = head, h2 = s.next;
    		s.next = null;
    		h2 = Reverse(h2);
    		ListNode final = new ListNode(Int32.MinValue);
    		ListNode tail = final;
    		while (h1 != null && h2!=null)
    		{
    			//Add head of list 1
                            tail.next = h1;
    			tail = h1;
    			h1 = h1.next;
                
                           //add head of list 2
    			tail.next = h2;
    			tail = h2;
    			h2 = h2.next;	
    		}
            
    		if(h1!=null)
    		    tail.next = h1;
            
    		if(h2!=null)
    		    tail.next = h2;
    		head = final.next;
        }
        private static ListNode Reverse(ListNode head)
    	{
    		ListNode rev = null;
    		while (head != null)
    		{
    			ListNode temp = head;
    			head = head.next;
    			temp.next = rev;
    			rev = temp;
    		}
    		return rev;
    	}

Log in to reply
 

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