[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/feixiangcode/algorithm/master/Week_01/id_21/LeetCode_021_021.cpp [Back]  [Original]

/**
 * 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 == nullptr) return l2;
    if (l2 == nullptr) return l1;
    ListNode* dummy = new ListNode(0);
    ListNode* p = dummy;
    while(l1 != nullptr && l2 != nullptr) {
      if (l1->val val) {
        p->next = l1;
        l1 = l1->next;
      } else {
        p->next = l2;
        l2 = l2->next;
      }
      p = p->next;
    }
    if (l1 != nullptr) p->next = l1;
    else p->next = l2;
    
    p = dummy->next;
    delete dummy;
    return p;
  }
};

Web Proxy Viewer  |  New URL  |  Original Page