高质量代码

将一个字符串转化为整数。此处以数的大小不超过int范围为例,如果更大的范围则需要对应做相应处理。

#include<iostream>

usingnamespace std;

/*写一个int范围内的string转化为int型的函数*/

intmyFun(string str)

{

    const int n = str.size();

    int flag = 1;

    if (n == 0)  

        return 0; //判断字符串为空的情况

    int result = 0;

    int i = 0;

    if (str[i] == '-')//判断负数

    {

        flag = -1;

        i++;

    }

    else if (str[i] > '9' || str[i] <'0')

    {

        cout<<"error";

        return 0.0;

    }

    while (i < n)

    {

        if(str[i] > '9' || str[i] < '0')//每次判断字符串元素是否符合数字转化要求

        {

            cout<<"error2";

            return 0;

        }

        result = result * 10 + str[i] - '0';

        i++;

    }

    result*= flag;

    return result;

}

intmain()

{

    string d;

    while(cin>>d)

    cout<<myFun(d);

    return 0;

}

2 找出链表倒数第k个节点 注意此处三点:1 链表指针是否为空, 2 链表长度是否小于k, 3 unsigned很有陷阱啊,循环处如果k = 0则一直循环(不加->next判断以判断链表长度情况下简直崩溃)

struct ListNode
{
    int num;
    ListNode* next;
    ListNode(int d)
    {
        num = d;
        next = NULL;
    }
};
ListNode* indKthToTail(ListNode* pListHead, unsigned int k)
{
    if (pListHead == NULL || k == 0)
        return NULL;
    ListNode *before = pListHead, *after = pListHead;
    unsigned t = 0;
    while (t < k - 1 && before->next != NULL)//unsigned int的情况下t < k - 1永远为true,啊啊啊啊,好大的陷阱啊
    {
        before = before->next;
        t++;
    }
    if (t == k - 1)
    {
        while (before->next != NULL)
        {
            cout<<"rr"<<endl;


            before = before->next;
            after = after->next;
        }
    return after;
    }
    else
        return NULL;


}
int main()
{
    int d;
    ListNode* head = new ListNode(0);
    ListNode* p = head;
    int i = 0;
    while(cin>>d)
    {
        ListNode* q = new ListNode(d);
        p->next = q;
        p = p->next;
        i++;
    }
    ListNode* result = indKthToTail(head->next, 0);
    if (result != NULL)
    cout<<result->num;
    else
    cout<<"error";
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值