合并两个排序的链表
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:
一、设立pPoint1指向第一个链表,pPoint2指向第二个链表,newPoint作为新链表的指针,比较pPoint1与pPoint2指针所指数据的大小,确定链表的next的指向
注:ListNode* pPoint1的指针的引用为ListNode*& pPoint1
/* 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 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; ListNode *pPoint1 = pHead1; ListNode *pPoint2 = pHead2; ListNode *newPoint ,*newPointTemp; newPoint = isMin(pPoint1,pPoint2); newPointTemp = newPoint; while(pPoint1 != NULL && pPoint2!= NULL) { newPointTemp->next = isMin(pPoint1,pPoint2); newPointTemp = newPointTemp->next; } if(pPoint1 == NULL ) newPointTemp->next = pPoint2; else newPointTemp->next = pPoint1; return newPoint; } ListNode* isMin(ListNode*& pPoint1,ListNode*& pPoint2) { ListNode *temp; if(pPoint1->val <= pPoint2->val) { temp = pPoint1; pPoint1 = pPoint1->next; } else { temp = pPoint2; pPoint2 = pPoint2->next; } return temp; } };
二、采用递归的方式,较难理解
/* 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 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; if(pHead1->val <= pHead2->val) { pHead1->next = Merge(pHead1->next,pHead2); return pHead1; } else { pHead2->next = Merge(pHead1,pHead2->next); return pHead2; } } };