继续面试题,明天去面试了,附答案
class String{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
实现类中的四个函数:
String::String(const char* str)
{
if(str == NULL)
{
m_data = new char[1];
m_data[0] = ' ';
}
else
{
m_data = new char[sizeof(str)+1];
strcpy(m_data,str);
}
}
String::String(const String &other)
{
m_data = new char[sizeof(other.m_data)+1];
strcpy(m_data,other.m_data);
}
String::String & operate =(const String &other)
{
if(this == &other)
{
return *this;
}
delete[] m_data;
m_data = new char[sizeof(other.m_data)+1];
strcpy(m_data,other.m_data);
return *this;
}
String::~String(void)
{
delete[] m_data;
}
一个链表的结点结构
struct Node
{
int data ;
Node *next ;
};
typedef struct Node Node ;
已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序。
Node * Togeter(Node *head1 , Node *head2)
{
if(head1 == NULL) return head2;//如果head1==NULL return head2
if(head2 == NULL) return head1;
Node* head = NULL;//定义3个辅助Node*
Node* p1 = NULL;
Node* p2 = NULL;
if(head1->data < head2->data)
{
head = head1;
p1 = head1->next;
p2 = head2;
}
else
{
head = head2;
p1 = head2->next;
p2 = head1;
}
Node* pCur = head;
while(p1 != NULL&& p2 != NULL)
{
if(p1->data <= p2->data)
{
pCur->next = p1;
pCur = p1;
p1 = p1->next;
}
else
{
pCur->next = p2;
pCur = p2;
p2 = p2->next;
}
}
if(p1 != NULL) pCur->next = p1;
if(p2 != NULL) pCur->next = p2;
return head;
}