标签:tno 依次 nbsp question turn 返回 next title str
/* 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; } };
标签:tno 依次 nbsp question turn 返回 next title str
原文地址:https://www.cnblogs.com/zmm1996/p/11902428.html