菱纱梦

导航

Merge Two Sorted Lists <LeetCode>

---恢复内容开始---

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  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
12         if(l1==NULL||l2==NULL)
13         {
14             if(NULL!=l1)  return l1;
15             else return l2;
16         }
17         else 
18         {
19             ListNode *head;
20             if(l1->val<=l2->val)   head=l1;
21             else head=l2;
22             ListNode *up=head;
23             ListNode *list1=l1;
24             ListNode *list2=l2;
25             while(list1!=NULL&&list2!=NULL)
26             {
27                 ListNode *temp;
28                 if(list1->val<=list2->val)
29                 {
30                     temp=list1;
31                     list1=list1->next;
32                 }
33                 else
34                 {
35                     temp=list2;
36                     list2=list2->next;
37                 }
38                 up->next=temp;
39                 up=temp;
40             }
41             if(list1!=NULL||list2!=NULL)
42             {
43                 if(list1!=NULL)
44                 {
45                     up->next=list1;
46                 }
47                 else  up->next=list2;
48             }
49             return head;
50         }
51     }
52 };

 

posted on 2014-08-31 15:46  菱纱梦  阅读(156)  评论(0编辑  收藏  举报