[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;
  }
};

 

posted @ 2018-11-23 13:30  Ruohua3kou  阅读(125)  评论(0编辑  收藏  举报