首页 > 代码库 > Merge Two Sorted Lists

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {14         15             if (l1==null || l2==null) {16                 if (l1 != null) {17                     return l1;18                 }19                 if (l2 != null) {20                     return l2;21                 }22                 return null;23             }24             ListNode first;25             ListNode curr;26             if (l1.val < l2.val) {27                 curr=l1;28                 l1=l1.next;29             }else {30                 curr=l2;31                 l2=l2.next;32             }33             first=curr;34             while (l1!=null && l2!=null) {35                 if (l1.val<l2.val) {36                     curr.next=l1;37                     l1=l1.next;38                     curr=curr.next;39                 }else {40                     curr.next=l2;41                     l2=l2.next;42                     curr=curr.next;43                 }44             }45             if (l1!=null) {46                 curr.next=l1;47             }48             if (l2!=null) {49                 curr.next=l2;50             }51             return first;52     }53 }

 

Merge Two Sorted Lists