Java: Reverse 2nd half of the list and merge into the first list


  • 0
    C
    public void reorderList(ListNode head) {
            if(head==null || head.next == null || head.next.next==null)
                return;
            ListNode slow=head;
            ListNode fast = slow.next.next;
            while(fast!=null){
                slow=slow.next;
                fast=fast.next;
                if(fast!=null)
                    fast=fast.next;
            }
            fast = slow.next;
            slow.next=null;
            fast = reverse(fast);
            slow = head;
            while(fast!=null){
                ListNode tempSlow = slow.next;
                ListNode tempFast = fast.next;
                slow.next = fast;
                slow = tempSlow;
                fast.next = tempSlow;
                fast = tempFast;
            }
        }
        
        public ListNode reverse(ListNode head){
            if(head==null || head.next == null)
                return head;
            
            ListNode cur,temp,prev;
            cur = head;
            prev=null;
            while(cur!=null){
                temp = cur;
                cur = cur.next;
                temp.next = prev;
                prev = temp;
            }
            return prev;
        }

Log in to reply
 

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