将两个链表合并成一个
输入两个链表节点指针
输出,链表节点
要求:节点不是新建的,而是原来的两个链表中的节点
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode(0); ListNode* currentNode; head->next = NULL; currentNode = head; while(l1 || l2){ if(l1&&l2){ if(l1->val < l2->val){ currentNode->next = l1; l1 = l1->next; }else{ currentNode->next = l2; l2 = l2->next; } }else if(l1){ currentNode->next = l1; l1 = l1->next; }else if(l2){ currentNode->next = l2; l2 = l2->next; } currentNode = currentNode->next; } currentNode->next = NULL; currentNode = head->next; delete head; return currentNode; }
执行用时 : 20 ms, 在Merge Two Sorted Lists的C++提交中击败了10.56% 的用户
内存消耗 : 10.1 MB, 在Merge Two Sorted Lists的C++提交中击败了0.38%的用户
按照惯例,学习一下最速解法:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode *res = new ListNode(-1), *cur = res; while(l1 && l2) { if(l1->val <= l2->val) { cur->next = l1; cur = cur->next; l1 = l1->next; } else { cur->next = l2; cur = cur->next; l2 = l2->next; } } if(l1) { cur->next = l1; } if(l2) { cur->next = l2; } return res->next; }
起码从逻辑上就比我简单得多。
首先最明显的是当只有一个链表的时候就不进行汇合,而是直接赋值,这样就不用操作后面的东西。
其他的和我差不多。不过没有delete自己new的东西。
所以改进:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head = new ListNode(0); ListNode* currentNode; head->next = NULL; currentNode = head; while(l1 || l2){ if(l1&&l2){ if(l1->val < l2->val){ currentNode->next = l1; l1 = l1->next; }else{ currentNode->next = l2; l2 = l2->next; } }else if(l1){ currentNode->next = l1; break; }else if(l2){ currentNode->next = l2; break; } currentNode = currentNode->next; } currentNode = head->next; delete head; return currentNode; }
就是这样。但是逻辑不够清晰。要分析清楚在进行编码。
转载请标明出处:21 Merge Two Sorted Lists
文章来源: https://blog.csdn.net/cxhttt/article/details/88862893