我试图实现一个代码来将包含整数变量的节点插入已经排序或者没有元素的双向链表中。我已经提供了一个文件来测试我的代码是否工作。我的代码编译得很好,只是测试每次都会使我的代码失败。在双向链表中排序插入
下面是我的排序插入
void List<T>::insertSorted(T item)
{
ListItem<T> *temp, *temp2;
ListItem<T>* a=new ListItem<T>(item); //creates a node with our input item
if(head==NULL)
{
head=a; //if the list is empty, set head equal to the new
//node
}
//Following two conditions check whether head is the sole item in the list
//(i.e head->next==NULL), and then insert our node in it accordingly.
else if(head->value > item && head->next==NULL)
{
a->next=head;
head->prev=a;
head=a;
}
else if(head->value < item && head->next==NULL)
{
head->next=a;
a->prev=head;
}
//This piece checks whether our list has more than one nodes, and adds
//the input node accordingly.
else if(head->next!=NULL)
{
temp=head->next; //here i'm taking two consecutive nodes
//which in the first case are head->next and head;
temp2=head;
while(temp!=NULL)
{
//if our value can be sandwiched between two nodes then do this
if(temp->value > item && temp2->value < item)
{
temp2->next=a;
a->prev=temp2;
a->next=temp;
temp->prev=a;
break;
}
//go to the next two consecutive nodes
temp=temp->next;
temp2=temp2->next;
//if one of our node is null (i.e we've reached the end of
//the list, do the following
if(temp2->value <= item && temp==NULL)
{
temp2->next=a;
a->prev=temp2;
break;
}
}
}
}
这显然是错误的代码。我在这里做错了什么?
询问调试器。 – 2013-02-15 08:12:53
我对编程有点新手,相信我一直在努力做到这一点。 – mrsinister 2013-02-15 08:14:01
'temp2-> next = a; A->先前= TEMP2; A->下一=温度; temp-> prev = a;'< - 如果你正在为你的变量使用一些有意义的名字,在试图理解你的代码实际在做什么时它会帮助你很多。 – LihO 2013-02-15 08:14:24