LeetCode21. Merge Two Sorted Lists
2016-10-13 23:31
405 查看
LeetCode21. 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.
思路
可以设置一个新链表newhead,逐个比较l1,l2中的节点元素大小,将小的插入到新链表中。比较完后,将l1,l2中剩余的结点也插入到新链表中。代码实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { //链表为空 if(l1==NULL || l2==NULL) { if(l1==NULL) return l2; if(l2==NULL) return l1; } //确定新链表头结点 ListNode* newhead=new ListNode(0); ListNode* p3; p3=newhead; while(l1 && l2){ ListNode* tmp=new ListNode(0); if(l1->val<=l2->val){ tmp->val=l1->val; p3->next=tmp; p3=tmp; l1=l1->next; } else if(l1->val>l2->val){ tmp->val=l2->val; p3->next=tmp; p3=tmp; l2=l2->next; } } //剩余结点 while(l1){ ListNode* tmp=new ListNode(0); tmp->val=l1->val; p3->next=tmp; p3=tmp; l1=l1->next; } while(l2){ ListNode* tmp=new ListNode(0); tmp->val=l2->val; p3->next=tmp; p3=tmp; l2=l2->next; } newhead = newhead->next; return newhead; } };
ps: 之前写过几乎相同的代码,结果这一次写又出现了意想不到的错误(第一个while循环里面没有用else if而用了if,其实这时l1可能已经发生了变化)。所以说不要眼高手低,再简单的题都有可能错误。
鸡汤
细节决定成败相关文章推荐
- leetcode解题报告21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists 两个有序列表合成一个
- LeetCode 21. Merge Two Sorted Lists 题解 —— Java
- Leetcode题解 21. Merge Two Sorted Lists
- leetcode_效率题解_[python/C++]_21. Merge Two Sorted Lists(合并2个有序链表)
- LeetCode题解(Week2):21. Merge Two Sorted Lists
- 2018.1.8 LeetCode 21. Merge Two Sorted Lists 【链表的基本运用】
- 21. Merge Two Sorted Lists-leetcode-java
- leetcode 21. Merge Two Sorted Lists
- LeetCode_21. Merge Two Sorted Lists
- [LeetCode] 21. Merge Two Sorted Lists 解题思路
- LeetCode-Easy部分中标签为LinkedList 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists leetcode Python 2016 new Season
- 【LeetCode】21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists 两个单向链表合并 指针与解指针
- LeetCode 21. Merge Two Sorted Lists
- leetcode21. Merge Two Sorted Lists
- LeetCode: 21. Merge Two Sorted Lists