《剑指Offer》第一章

第一题:实现atoi函数

这个题目看起来简单,写bug free比较困难。非法输入、是否有正负号,是否溢出、非法输入如何处理错误

int Errno = 0;
int StrToInt(const string &str)
{
	long long result = 0;	//用long long来存储结果,检测溢出
	int flag = 1;			//表示正负号
	int i = 0;
	//判断第一位是否为符号位,如果是,则i前进处理
	if (str[i] == '-')
	{
		flag = -1;
		++i;
	}
	else if (str[i] == '+')
	{
		++i;
	}
	for (; i < str.size(); i++)
	{
		if (str[i] >= '0' && str[i] <= '9')
		{
			result = result * 10 + str[i] - '0';
		}
		else
		{
			//输入非法,置全局变量为1,返回0
			Errno = 1;
			return 0;
		}
		if (flag == 1 && result > INT_MAX)
		{
			//溢出,置全局变量为1,返回0
			Errno = 1;
			return 0;
		}
		if (flag == -1 && result < INT_MIN)
		{
			//溢出,置全局变量为1,返回0
			Errno = 1;
			return 0;
		}
	}
	return flag*result;
}


第二题:删除链表中等于X的节点

这个题目思路应该都比较清楚,但是写出bug free不容易。值为X的节点不一定只要一个。

ListNode *Delete(ListNode *head, int x)
{
	//删除前面等于x的节点
	while (head != NULL && head->val == x)
		head = head->next;
	if (head == NULL)
		return NULL;
	//因为到这一步head肯定不为NULL,所以直接把pAhead设置为head->next
	ListNode *pAhead = head->next;
	ListNode *pBehind = head;

	while (pAhead != NULL)
	{
		if (pAhead->val == x)
		{
			pBehind->next = pAhead->next;
			pBehind = pBehind->next;
			pAhead = pBehind->next;
		}
		else
		{
			pAhead = pAhead->next;
			pBehind = pBehind->next;
		}
	}
	return head;
}

第三题:求链表的倒数第K个节点

这个题目也很常见,但是也很容易出错,比如链表的节点总数少于k个等,先走k-1步

ListNode* FindKthToTail(ListNode *pHead, int k)
{
	if (pHead == NULL)
		return NULL;
	ListNode *pAhead = pHead;
	ListNode *pBehind = NULL;
	int i = 0;
	for (i = 0; i < k - 1 && pAhead != NULL; i++)
		pAhead = pAhead->next;
	//判断节点总数是否小于k
	if (i < k - 1)
		return NULL;
	pBehind = pHead;
	while (pAhead->next != NULL)
	{
		pAhead = pAhead->next;
		pBehind = pBehind->next;
	}
	return pBehind;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值