题目:https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
我的方法:直接遍历
比较简单,直接看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy;
ListNode* tail = &dummy;
ListNode* cur1 = l1;
ListNode* cur2 = l2;
while(cur1 && cur2) {
if(cur1->val <= cur2->val) {
tail->next = cur1;
cur1 = cur1->next;
}else{
tail->next = cur2;
cur2 = cur2->next;
}
tail = tail->next;
tail->next = nullptr;
}
if(cur1) {
tail->next = cur1;
}
if(cur2) {
tail->next = cur2;
}
return dummy.next;
}
};
网友评论