严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Merge two sorted LinkedLists

Go down

Merge two sorted LinkedLists Empty Merge two sorted LinkedLists

Post by Admin Sun Oct 22, 2017 2:13 pm

public ListNode mergeTwoLists(ListNode listA, ListNode listB){
         if(listB == null)
           return listA;
         if(listA == null)
             return listB;
       
         ListNode fakehead = new ListNode(-1);
         ListNode ptr = fakehead;
         while(listB!=null&&listA!=null){
            if(listB.val<listA.val){
                ptr.next = listB;
                ptr = ptr.next;
                listB = listB.next;
            }else{
                ptr.next = listA;
                ptr = ptr.next;
                listA = listA.next;
            }
        }
       
        if(listB!=null)
            ptr.next = listB;
        if(listA!=null)
            ptr.next = listA;
       
        return fakehead.next;
    }

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum