LeetCode 21:Merge Two Sorted Lists
来源:互联网 发布:nginx 域名指向目录 编辑:程序博客网 时间:2024/04/30 20:43
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.
将两个已排序的链表合并成一个新链表,新列表应该包含前两个链表的所有节点。
好这道题一开始卡了我好几个小时,在我千辛万苦终于写出来一个可以用的版本时,它告诉我超!时!了!嗯,于是我灵光一闪,花了5分钟写了另一个版本,于是通过了。。。为什么这么简单的方法我之前没想到啊魂淡!为什么突然又想出来了啊魂淡!
/** * 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 { ListNode *temp,*head; temp=head; while(l1->next&&l2->next) { if(l1->val>l2->val) { head->next=l2; l2=l2->next; } else { head->next=l1; l1=l1->next; } head=head->next; } if(!l1->next&&l2->next) { while(l2->next) { if(l1->val>l2->val) { head->next=l2; l2=l2->next; head=head->next; } else { head->next=l1; l1->next=l2; break; } } } else if(!l2->next&&l1->next) { while(l1->next) { if(l2->val>l1->val) { head->next=l1; l1=l1->next; head=head->next; } else { head->next=l2; l2->next=l1; break; } } } if(l1->val<l2->val) { head->next=l1; l1->next=l2; } else { head->next=l2; l2->next=l1; } return temp->next; } }};*/class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head=new ListNode(0); ListNode* temp=head; while(l1&&l2) { if(l1->val<l2->val) { head->next=l1; l1=l1->next; } else { head->next=l2; l2=l2->next; } head=head->next; } if(!l1) head->next=l2; if(!l2) head->next=l1; return temp->next; }};
0 0
- 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
- Leetcode 21 Merge Two Sorted Lists
- 【leetcode】【单链表】【21】Merge Two Sorted Lists
- LeetCode 21 - Merge Two Sorted Lists
- 在Async中使用Toast
- 神经网络_学习笔记1215
- java面试题
- 掌握设计模式
- 师父
- LeetCode 21:Merge Two Sorted Lists
- Android应用架构
- Qt中网络编程(网络接口,TCP,UDP)
- SQL注入与防范(PreparedStatement的优点)----JDBC-3
- hw员工培养计划
- SlidingMenu-Fragment
- STL算法库-修改序列式操作(一)
- OI? OI!
- 设计模式中类的关系