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 * 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 ListNode *dummy=new ListNode(0),*tail=dummy; 13 14 while(l1!=NULL&&l2!=NULL){ 15 if(l1->val<l2->val){ 16 tail->next=l1; 17 l1=l1->next; 18 }else{ 19 tail->next=l2; 20 l2=l2->next; 21 } 22 tail=tail->next; 23 } 24 //检测还有没有剩余 25 if(l1){ 26 tail->next=l1; 27 } 28 if(l2){ 29 tail->next=l2; 30 } 31 ListNode *head=dummy->next; 32 delete dummy; 33 return head; 34 } 35 };