和并两个有序链表

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
      ListNode* dummy = new ListNode(-1); // 作为一个头节点
      ListNode* cur = dummy;			  // 作为一个移动哨兵,进行移动

      while(list1 != nullptr && list2 != nullptr) {
        if (list1->val < list2->val) {
          cur->next = list1;
          list1 = list1->next;
        }else{
          cur->next = list2;
          list2 = list2->next;
        }
        cur = cur->next;
      }

      if (list1 != nullptr) {
        cur->next = list1;
      }
      else if (list2 != nullptr) {
        cur->next = list2;
      }
      
      return dummy->next; // 返回头节点
    }

你可能感兴趣的:(数据结构,双向链表)