Merge two sorted lists

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.