标签:
No.21 Merge Two Sorted List
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 { 13 if(l1 == NULL) 14 return l2; 15 if(l2 == NULL) 16 return l1; 17 18 ListNode *head, *current; 19 //使用头结点的方法:ListNode helper = new ListNode(0); helper.next = head1; 20 //他们都用的是将l2的节点插入l1中的方法 21 22 if(l1->val <= l2->val) 23 { 24 head = l1; 25 l1 = l1->next; 26 } 27 else 28 { 29 head = l2; 30 l2 = l2->next; 31 } 32 33 current = head; 34 35 while(l1 && l2) 36 { 37 if(l1->val <= l2->val) 38 { 39 current->next = l1; 40 l1 = l1->next; 41 } 42 else 43 { 44 current->next = l2; 45 l2 = l2->next; 46 } 47 current = current->next; 48 } 49 50 if(l1) 51 current->next = l1; 52 if(l2) 53 current->next = l2; 54 55 return head; 56 } 57 };
标签:
原文地址:http://www.cnblogs.com/dreamrun/p/4528298.html