【leetcode】 21. 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) { 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 }

 

posted @ 2016-07-05 00:29  godlei  阅读(143)  评论(0编辑  收藏  举报