问题描述:
将两个已经排序的单向链表合并为一个链表,要求空间复杂度尽可能的小。
本题两个注意事项:
第一,任何题目都有时间和空间的要求,所以不要想当然地重建一个链表,这样会带来空间的浪费
第二,该题可以用两种方法来实现,递归和循环,在写答案之前,可以和面试官交流
具体代码如下
(i)递归方法:
struct listNode
{
int data;
listNode *next;
};
listNode *mergeList(listNode *p1,listNode *p2)
{
if(p1==NULL)
{
return p2;
}
if(p2==NULL)
{
return p1;
}
listNode *next;
if(p1->data<p2->data)
{
next=mergeList(p1->next,p2);
p1->next=next;
return p1;
}else
{
next=mergeList(p1,p2->next);
p2->next=next;
return p2;
}
}
(ii)循环解法:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct listNode
{
int data;
listNode *next;
};
listNode *mergeList(listNode *p1,listNode *p2)
{
if(p1==NULL)
{
return p2;
}
if(p2==NULL)
{
return p1;
}
listNode *newHead,*cur;
if(p1->data<p2->data)
{
newHead=p1;
p1=p1->next;
}else
{
newHead=p2;
p2=p2->next;
}
cur=newHead;
while(p1!=NULL && p2!=NULL)
{
if(p1->data<p2->data)
{
cur->next=p1;
p1=p1->next;
cur=cur->next;
}else
{
cur->next=p2;
p2=p2->next;
cur=cur->next;
}
}
cur->next=p2->next==NULL?p1:p2;
return newHead;
}