leetcode-Merge Two Sorted Lists
来源:互联网 发布:redmine windows 安装 编辑:程序博客网 时间:2024/06/05 06:52
Question:
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.
Subscribe to see which companies asked this question.
Solution:
/** * 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; } if(l2 == NULL){ return l1; } ListNode* head,*cur; if(l1->val >l2->val){ head = l2; l2 = l2->next; } else{ head = l1; l1 = l1->next; } cur = head; while(l1 != NULL && l2 != NULL){ if(l1->val > l2->val){ cur->next = l2; cur = l2; l2 = l2->next; } else{ cur->next = l1; cur = l1; l1 = l1->next; } } if(l1 == NULL){ cur->next = l2; } else{ cur->next = l1; } return head; }};
总结:
刚开始做的时候,还在考虑要不要判断两个链表升降序的
问题,就先用升序测试了一下,结果ac.
0 0
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- Leetcode Merge Two Sorted Lists
- SCPPO(八):登录实现逻辑
- PHP Array方法归纳总结
- LeetCode第二天
- TensorFlow深度学习笔记 Logistic Classification
- Mybatis 高级结果映射 ResultMap Association Collection
- leetcode-Merge Two Sorted Lists
- springMvc的环境的搭建
- TensorFlow深度学习笔记 逻辑回归 实践篇
- 第三天AsyncTask
- 图解冰河木马一次使用过程
- Java中异常的理解
- java.lang.OutOfMemoryError问题与heap获取
- TensorFlow深度学习笔记 Stochastic Optimization
- js实现跳转到顶部或者底部