题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
方法一
新建一个链表,遍历两个输入的链表,进行节点值的比较,新建链表的next指向值较小的节点。代码
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* head = new ListNode(0); head->next = NULL; ListNode* p = head; while( pHead1 != NULL || pHead2 != NULL ) { if( pHead1 == NULL ) { p->next = pHead2; return head->next; } else if( pHead2 == NULL ) { p->next = pHead1; return head->next; } else if( pHead1->val < pHead2->val ) { p->next = pHead1; p = p->next; pHead1 = pHead1->next; } else { p->next = pHead2; p = p->next; pHead2 = pHead2->next; } } return head->next; } };
方法二
利用递归完成合并,步骤如下:Step1.定义一个指向新链表的指针,暂且让它指向NULL;
Step2.比较两个链表的头结点,让较小的头结点作为新链表的头结点;
Step3.递归比较两个链表的其余节点,让较小的节点作为上一个新节点的后一个节点;
代码
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1==nullptr) return pHead2; if(pHead2==nullptr) return pHead1; ListNode* res=nullptr; if(pHead1->val>=pHead2->val){ res=pHead2; res->next=Merge(pHead1,pHead2->next); }else{ res=pHead1; res->next=Merge(pHead1->next,pHead2); } return res; } };