1. 程式人生 > >[leetcode] 21. Merge Two Sorted Lists (Easy)

[leetcode] 21. Merge Two Sorted Lists (Easy)

合併連結串列

Runtime: 4 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists.

class Solution
{
public:
  ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
  { //1 2 4 . 1 3 4
    ListNode *res = new ListNode(0);
    ListNode *cur = res;
    while (l1 != NULL && l2 != NULL)
    {
      
if (l1->val <= l2->val) { cur->next = l1; l1 = l1->next; cur = cur->next; } else { cur->next = l2; l2 = l2->next; cur = cur->next; } } if (l1 != NULL) cur->next = l1; else cur
->next = l2; return res->next; } };