我在做算法作业的时候,写出来一个程序,提交对答案之后,只是部分,有一部分测试程序发现超时,不知为何,也不知道如何解决,请大牛告诉原因以及解决方法!
以下为我写的代码:
#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;
}
望大牛们不吝赐教。