首页 > 其他 > 详细

Merge Two Sorted Lists

时间:2014-10-13 12:21:20      阅读:208      评论:0      收藏:0      [点我收藏+]
 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.next
26                  ListNode temp=current;
27                  current=head.next;
28                  head.next=temp;
29                  head=temp;
30              }
31              else
32              head=head.next;
33             }
34             else
35             {  //说明一个链表后面没有了
36                 head.next=current;
37                 break;
38             }
39         }
40         
41         return first;
42         
43         
44     }
45 }

 

Merge Two Sorted Lists

原文:http://www.cnblogs.com/sweetculiji/p/4021825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!