Leetcode21--->Merge Two Sorted Lists(合并两个排序的单链表)

题目: 给出两个排序的单链表,合并两个单链表,返回合并后的结果;

解题思路:

解法还是很简单的,但是需要注意以下几点:

1.  如果两个链表都空,则返回null;

2.  如果链表1空,则返回链表2的头节点;反之,如果链表2为空,则返回链表1的头节点;

3.  两个链表都不空的情况下:

   比较两个链表的头节点的值,哪个小,则新链表的头节点为哪个;

  举例:l1: 1->3->5; l2:2->4->6->7;则:head = l1的头节点,此时head.next = l1.next 或者 l2

代码如下:

 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 ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11         if(l1 == null && l2 == null)
12             return null;
13         if(l1 == null)
14             return l2;
15         if(l2 == null)
16             return l1;
17         ListNode head = null;
18         if(l1.val > l2.val)
19         {
20              head = l2;
21              head.next = mergeTwoLists(l1, l2.next);
22         }
23         else
24         {
25              head = l1;
26              head.next = mergeTwoLists(l1.next, l2);
27         }
28         return head;
29     }
30 }

 

posted @ 2016-09-17 20:44  小叶子leavescy  阅读(2254)  评论(0编辑  收藏  举报