题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
非递归版本:
1.新建一个头结点mergeHead,和尾节点 current.
2.比较两个链表的头节点,确定mergeHead, 将current指向mergeHead.
3.依次比较两个链表节点(在都不为空的情况下),current->next保存数值小的节点, current后移
4.若链表为空, current->next指向 非空链表
5.返回mergeHead.
/* 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 * mergeHead = nullptr; //新建一个头结点mergeHead,和尾节点 current. ListNode * current = nullptr; if(pHead1->val <= pHead2->val) //比较两个链表的头节点,确定mergeHead { //将current指向mergeHead. mergeHead = current =pHead1; pHead1 = pHead1->next; } else { mergeHead = current = pHead2; pHead2 = pHead2->next; } while(pHead1!=NULL && pHead2!=NULL) //遍历两个链表 { if(pHead1->val <= pHead2->val) { current->next = pHead1; //current保存小的节点 current = current->next; //current后移 pHead1 = pHead1->next; //该链表后移 } else { current->next = pHead2; current = current->next; pHead2 = pHead2->next; } } if(pHead1 == NULL) { current->next = pHead2; } if(pHead2 == NULL) { current->next = pHead1; } return mergeHead; } };