Leetcode 21. Merge Two Sorted Lists(C++)
来源:互联网 发布:网络公选课答案 编辑:程序博客网 时间:2024/04/29 17:11
问题:
Merge Two Sorted Lists (将两个有序单链表合成一个有序的单链表)
参考链接:
1、[LeetCode]21.Merge Two Sorted Lists
2、LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
思想1:定义一个新的链表,比较两个链表,小的放进新链表中,谁小谁跳到下一个节点与另一个链表的当前节点比较。
图解:
注意点:若其中一个链表为空,则直接返回另一个;
定义一个新链表,需要至少定义两个节点:头结点,用于返回;当前节点用于对链表元素赋值以及跳转到下一个节点。
代码:
/** * 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) return l2; if (!l2) return l1; ListNode* head = new ListNode(-1);//定义头结点和当前位置节点:静节点和动节点 ListNode *tmp = head; while(l1&&l2) { if (l1->val>l2->val) { tmp->next=l2; l2=l2->next; } else { tmp->next=l1; l1=l1->next; } tmp=tmp->next; } while(!l1&&l2) { tmp->next=l2; l2=l2->next; tmp=tmp->next; } while(!l2&&l1) { tmp->next=l1; l1=l1->next; tmp=tmp->next; } return head->next; }};
思想2:递归法:自己调用自己,分析此题的特点满足:函数输出可以作为输入,进而更新输入,直到两个链表都为空。
代码:
class Solution {public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2;//返回较长的链表; if(l2 == NULL) return l1; if(l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1;//跳到下一个节点 } else { l2->next = mergeTwoLists(l2->next, l1); return l2;//将短链表l1按顺序插进l2中。 } }};
0 0
- Leetcode 21. Merge Two Sorted Lists(C++)
- 【C++】【LeetCode】21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists leetcode(lists)
- [C++]LeetCode: 13 Merge Two Sorted Lists
- 【leetcode c++】21 Merge Two Sorted Lists
- 【LeetCode-21】 Merge Two Sorted Lists(C++)
- Leetcode c语言- Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists(C++)
- 【LeetCode】21. Merge Two Sorted Lists C语言
- [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] 21.Merge Two Sorted Lists
- [leetcode] 21.Merge Two Sorted Lists
- [leetcode] 21. Merge Two Sorted Lists
- c++第五次作业
- 主要介绍了secureCRT脚本的编写基础及对象和方法
- Git合并多个commit
- Java ThreadLocal 内部实现原理 (源代码分析)
- Android 服务(Service)
- Leetcode 21. Merge Two Sorted Lists(C++)
- 窗体之间传值(委托,事件,Owner,封装属性)
- Opencv常用函数
- JAVA.LANG.OUTOFMEMORYERROR: JAVA HEAP SPACE错误及处理办法
- POJ1321棋盘问题 搜索基础题
- Service生命周期最全面解析
- 欢迎使用CSDN-markdown编辑器
- Android Tint使用
- mysql登录及常用命令