首页 > 其他 > 详细

【leetcode】 21. Merge Two Sorted Lists

时间:2016-07-05 01:07:23      阅读:221      评论:0      收藏:0      [点我收藏+]

题目描述:

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) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
11         if(head1==null)
12             return head2;
13         if(head2==null)
14             return head1;
15         ListNode head=null;
16         ListNode current=null;
17         if(head1.val<=head2.val){
18             head=head1;
19             head1=head1.next;
20             head.next=null;
21         }
22         else{
23             head=head2;
24             head2=head2.next;
25             head.next=null;
26         }
27         current=head;
28         while(head1!=null&&head2!=null){
29             if(head1.val<=head2.val){
30                 current.next=head1;
31                 current=current.next;
32                 head1=head1.next;
33                 current.next=null;
34             }
35             else{
36                 current.next=head2;
37                 current=current.next;
38                 head2=head2.next;
39                 current.next=null;
40             }
41         }
42         if(head1!=null){
43             current.next=head1;
44         }
45         if(head2!=null){
46             current.next=head2;
47         }
48         return head;
49     }
50 }

 

【leetcode】 21. Merge Two Sorted Lists

原文:http://www.cnblogs.com/godlei/p/5642154.html

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