您的位置:首页 > 编程语言

高质量代码

2016-09-30 15:40 78 查看
将一个字符串转化为整数。此处以数的大小不超过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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: