今天的问题是链表的合并。使连接起来的链表依然有序。所以我们创建一个新的节点,两个链表比较,小的接在新节点后面,最后可能两个链表不一样长,我们去剩下的那个接在新的链表后面即可。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
// write code here
ListNode* node = new ListNode(0);
if(l1==NULL) return l2;
if(l2==NULL) return l1;
ListNode* head = node;
while(!(l1==NULL || l2==NULL)){
if(l1->val < l2->val){
head->next = l1;
l1 = l1->next;
}
else{
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
if(l1!=NULL) head->next = l1;
if(l2!=NULL) head->next = l2;
return node->next;
}
};