String (Linked List)

Requirements:
1. TString中动态申请内存时,no memory wastage is allowed throughout the execution.
2. Can’t request a fixed size of memory at a time (比如每次申请100MB固定大小空间的形式算违规).
3. 如果需要申请临时交换内存,也不能按固定大小申请,必须按需申请,使用完毕后立即释放.
4. 不允许使用string类,不允许定义数组,不允许使用任何形式的全局变量,动态内存申请必须是new/delete.
5. 实现!= 时,只有长度相等且对应位置字符值相等才认为相等,否则就是不等.
6. 要求+=的复杂度尽量低.

class TString;

class str {
	char *content;
	str *next;
	int len;
	friend TString;
};

class TString {
private:
	str *head;
	str *tail;
	int len_all;
public:
	TString();
	~TString();
	TString& operator+=(const char *);
	int length();
	bool operator!=(const char*);
};
TString::TString()
{
	head = new(nothrow) str;
	head->next = NULL;
	tail = head->next;
	len_all = 0;
}
TString::~TString()
{
	str *q, *p = head;
	while (p)
	{
		delete[]p->content;
		q = p->next;
		delete[]p;
		p = q;
	}
	head = NULL;
}
bool TString::operator!=(const char* b)
{
	str *p = head->next;
	int num = 0;
	while (p)
	{
		if (strncmp(b + num, p->content, p->len))
			return true;
		num += p->len;
		p = p->next;
	}
	return false;
}
TString& TString::operator+=(const char* s)
{
	int len_s = strlen(s);
	len_all += len_s;

	tail = new(nothrow)str[1];
	tail->content = new(nothrow)char[len_s + 1];
	tail->len = len_s;

	memcpy(tail->content, s, len_s + 1);
	tail = tail->next;

	tail = NULL;
	return *this;
}

int TString:: length()
{
	return len_all;
}

 

 

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *