The topics are as follows:
Merge two sorted linked lists and return it as a new list.
The analysis is as follows:
Simple, try it, 10 minutes on the Leetcode Web page and check the bug, the submission found that there is a spelling error, changed and then submitted to pass.
The code is as follows:
/** * 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;
Easy to write leaks.
} 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; }
};
Can compare this topic to merge two sorted array
Update:2015-03-23
1. Use the dummy head to simplify the code.
2. Ontology Tail->next = null This assignment, if deleted, has no effect on the result, so it is commented out. But in other topics, this assignment is important, otherwise the new list has no end point, causing the loop to proceed indefinitely.
18ms class Solution {public:listnode *mergetwolists (ListNode *l1, ListNode *l2) {listnode* Dummyhead = n
EW 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; }
};