Brushing notes (11)-merge two linked lists

Brushing notes (11)-merge two linked lists

Title description

Input two monotonically increasing linked lists, and output the combined list of the two linked lists. Of course, we need the synthesized linked list to satisfy the monotonous and non-decreasing rules.

Idea: Use recursive method

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* p, ListNode* q)
    {
        if(p==NULL)return q;
        if(q==NULL)return p;
        if(p->val<=q->val)
        {   p->next=Merge(p->next,q);
          return p;
        }
         else
         {
             q->next=Merge(p, q->next);
              return q;
         }
    }
};

 

Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105419392