两个链表一个升序一个降序,合并为升序链表

题目解析: 其实可以把题目拆解为:翻转链表+两个有序链表的合并。

代码:

#include 

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}

  void print() {
    printf("%d -> ",this->val);
    if(this->next !=nullptr){
      this->next->print();
    }
    else {
      printf("\n");
    }
  }
};


ListNode* reverseList(ListNode* head) {
  if(head == nullptr || head->next == nullptr)        return head;
  ListNode *reverse = reverseList(head->next);
  head->next->next = head;
  head->next = nullptr;
  return reverse;
}


ListNode* merge(ListNode* list1,ListNode* list2){

  ListNode *l2reverse = reverseList(list2);
  if(list1 == nullptr)
      return list2;
  if(list2 == nullptr)
      //return list1;
      return list1;


  ListNode *pMergeHead = nullptr;
  ListNode *current = nullptr;


  while(list1!=nullptr && l2reverse != nullptr)
  {
    if(list1->val <= l2reverse->val)
    {
      if(pMergeHead == nullptr)
      {
        current = pMergeHead = list1;
      }
      else
      {
        current->next = list1;
        current = current->next;

      }
      list1 = list1->next;

    }
    else
    {
      if(pMergeHead == nullptr)
      {
        current = pMergeHead = l2reverse;
      }
      else
      {
        current->next = l2reverse;
        current = current->next;

      }
      l2reverse = l2reverse->next;

    }

    //pMergeHead = pMergeHead->next;

  }
  if(list1 == nullptr)
  {
    current->next = l2reverse;
  }
  if(l2reverse == nullptr)
  {
    current->next = list1;
  }
  return pMergeHead;
}

int main() {
  ListNode n1(1);
  ListNode n2(3);
  ListNode n3(5);
  ListNode m1(6);
  ListNode m2(4);
  ListNode m3(2);

  n1.next = &n2;
  n2.next = &n3;
  m1.next = &m2;
  m2.next = &m3;
  //ListNode* rr = reverseList(&n1);
  //rr->print();
  n1.print();
  m1.print();
  ListNode* r = merge(&n1,&m1);

  r->print();
  return 0;
}



你可能感兴趣的:(两个链表一个升序一个降序,合并为升序链表)