leetcode:21 Merge Two Sorted Lists-每日编程第十七题
来源:互联网 发布:初入职场 知乎 编辑:程序博客网 时间:2024/06/05 07:09
Merge Two Sorted Lists
Total Accepted: 95133 Total Submissions: 281996 Difficulty: Easy
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.
思路:
1).轮流比较l1与l2的值,较小的值链接到新链上。如l1->val<=l2->val,将l1链接到新链上,然后递增l1。
2).重复1).直到l1或者l2为空。
3).最后将非空的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){ return l2; }else if(l2==NULL){ return l1; }else{ if(l1->val<=l2->val){ l1->next=mergeTwoLists(l1->next,l2); return l1; }else{ l2->next=mergeTwoLists(l1,l2->next); return 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){ return l2; }else if(l2==NULL){ return l1; } ListNode* head; if(l1->val<=l2->val){ head=l1; l1=l1->next; }else{ head=l2; l2=l2->next; } ListNode* p=head; while(l1!=NULL&&l2!=NULL){ if(l1->val<=l2->val){ p->next=l1; p=l1; l1=l1->next; }else{ p->next=l2; p=l2; l2=l2->next; } } if(l1==NULL){ p->next=l2; } if(l2==NULL){ p->next=l1; } return head; }};
递归:
0 0
- leetcode:21 Merge Two Sorted Lists-每日编程第十七题
- 【leetcode每日一题】NO21.Merge Two Sorted Lists
- leetcode 每日一题 21. Merge Two Sorted Lists
- LeetCode(21)Merge Two Sorted Lists
- [LeetCode 21] Merge Two Sorted Lists Solution
- [leetcode 21] Merge Two Sorted Lists
- LeetCode 21:Merge Two Sorted Lists
- LeetCode | #21 Merge Two Sorted Lists
- [Leetcode] 21 - Merge Two Sorted Lists
- leetcode.21------------Merge Two Sorted Lists
- [leetcode]21 Merge Two Sorted Lists
- Leetcode NO.21 Merge Two Sorted Lists
- leetcode[21 链表]Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- leetCode #21 Merge Two Sorted Lists
- leetcode 21 Merge Two Sorted Lists
- [Leetcode 21, Easy] Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists
- 我要带徒弟学JAVA架构 ( 写架构,非用架构 )
- PopupWindow的基本使用方法
- 添加php7到wamp后,启动apache提示扩展错误bug调试
- iOS KVC 和 KVO 简单论述
- 常用正则表达式大全
- leetcode:21 Merge Two Sorted Lists-每日编程第十七题
- 向上无缝滚动javascript
- 【飘逸的Python】 在Apache2中部署Tornado应用
- Android Dialog II-dialog的操作
- CAS认证系统基础
- android收集常用框架
- Python open读写文件实现脚本
- 使用行为树(Behavior Tree)实现游戏AI
- 向右无缝滚动javascript