第一题:实现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;
}
这个题目思路应该都比较清楚,但是写出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;
}