题解 | 合并两个排序的链表
合并两个排序的链表
http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
利用辅助栈存储序列,再生成新的链表
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode *newHead=NULL;
if(!pHead1&&!pHead2){
return newHead;
}
vector<int>ret;
while(pHead1&&pHead2){
if(pHead1->val<=pHead2->val){
ret.push_back(pHead1->val);
pHead1=pHead1->next;
}
else{
ret.push_back(pHead2->val);
pHead2=pHead2->next;
}
}
while(pHead1){
ret.push_back(pHead1->val);
pHead1=pHead1->next;
}
while(pHead2){
ret.push_back(pHead2->val);
pHead2=pHead2->next;
}
newHead=new ListNode(ret[0]);
ListNode* r=newHead;
for(int i=1;i<ret.size();i++){
ListNode* s=new ListNode(ret[i]);
r->next=s;
r=s;
}
return newHead;
}
};