题目如下:
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.
分析如下:
比较简单,试了一下,10分钟在leetcode网页上敲完且检查了一下bug,提交发现有个拼写错误,改了之后提交通过。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//28ms
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode* head=NULL;
ListNode* tail=NULL;
while(l1!=NULL&&l2!=NULL){
if(l1->val<l2->val){
if(head==NULL){
head=l1;
tail=head;
}else{
tail->next=l1;
tail=tail->next; //容易写漏!
}
l1=l1->next;
}else{
if(head==NULL){
head=l2;
tail=head;
}else{
tail->next=l2;
tail=tail->next;
}
l2=l2->next;
}
}
while(l1!=NULL){
if(head==NULL){
head=l1;
tail=head;
}else{
tail->next=l1;
tail=tail->next;
}
l1=l1->next;
}
while(l2!=NULL){
if(head==NULL){
head=l2;
tail=head;
}else{
tail->next=l2;
tail=tail->next;
}
l2=l2->next;
}
return head;
}
};
可以对比这道题目 merge two sorted array
update: 2015-03-23
1. 使用dummy head简化代码。
2. 本体中tail->next = NULL这个赋值如果删掉,对结果没有影响,所以就注释掉了。但是在其它一些题目中,这个赋值很重要,否则新list是没有终点的,导致循环无限进行。
// 18ms
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode* dummyHead = new ListNode(0);
ListNode* tail = dummyHead;
ListNode* headl1 = l1;
ListNode* headl2 = l2;
while (l1 != NULL && l2 != NULL) {
if(l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
tail = tail->next;
//tail->next = NULL;
} else {
tail->next = l2;
l2 = l2->next;
tail = tail->next;
//tail->next = NULL;
}
}
while (l1 != NULL) {
tail->next = l1;
l1 = l1->next;
tail = tail->next;
//tail->next = NULL;
}
while (l2 != NULL) {
tail->next = l2;
l2 = l2->next;
tail = tail->next;
//tail->next = NULL;
}
return dummyHead->next;
}
};