首页 > 代码库 > Merge Two Sorted Lists

Merge Two Sorted 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         if(l1==null) return l2;15         if(l2==null) return l1;16         ListNode head=l1.val<l2.val?l1:l2;17         ListNode current=l1.val<l2.val?l2:l1;18         ListNode first=head;//记录head头 最后返回19         20         while(true)21         {22             if(head.next!=null)23             {24              if(head.next.val>current.val)25              {  //让head挪到current current挪到head.next26                  ListNode temp=current;27                  current=head.next;28                  head.next=temp;29                  head=temp;30              }31              else32              head=head.next;33             }34             else35             {  //说明一个链表后面没有了36                 head.next=current;37                 break;38             }39         }40         41         return first;42         43         44     }45 }

 

Merge Two Sorted Lists