用双链表从尾端查找数据为什么会超时?

我在做算法作业的时候,写出来一个程序,提交对答案之后,只是部分,有一部分测试程序发现超时,不知为何,也不知道如何解决,请大牛告诉原因以及解决方法!



以下为我写的代码:

#include<iostream>
using namespace std;
class node{
public:
    int data;
    node *previous;
    node *next;
};

class list{
private:
    node *last;
    node *temp;
public:
    list():last(NULL),temp(NULL){}
    node *create_list();
    node *print_data();
    int getLength();
};

node *list::create_list()
{
    node *p = new node;
    p->previous = NULL;
    int x = 0;
    while(x >= 0)
    {
        temp = new node;
        cin>>x;
        p->data = x;                                    
        p->next = temp;
        temp->previous = p;
        p = temp;
        temp = NULL;
        delete temp;
    }
    last = p;
    p->next = NULL;
    return last;
}

int list::getLength()
{
    node *p = last->previous;
    int i = -1;
    while(p != NULL)
    {
        p = p->previous;
        i++;
    }
    return i;
}

node *list::print_data()
{
    int i;
    int n = -1;
    cin>>i;
    create_list();
    node *p = last;
    if(i<=0 || i>getLength())
    {
        cout<<"NULL"<<endl;
        return NULL;
    }
    while(i != n)
    {
        p = p->previous;
        n++;
    }
    cout<<p->data<<endl;
    return last;
}

int main()
{
    list l1;
    l1.print_data();
    return 0;
}
望大牛们不吝赐教。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值