首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

双向链表的安插函数

2013-11-06 
双向链表的插入函数templateclass Typebool DListType::Insert(int pos,Type &e) //在下标为 pos 位之

双向链表的插入函数
template<class Type>
bool DList<Type>::Insert(int pos,Type &e) //在  下标为 pos 位之后插入新的节点
{
if(pos<0 || pos>Length())
return false;
else                  
{
Node<Type> *newNode=new Node<Type>(e);
Node<Type> *tmp,*tmp1;
tmp=Locate(pos);
                 tmp1=tmp->next; 
tmp->next=newNode; 
newNode->pre=tmp;
newNode->next=tmp1;
tmp1->pre=newNode;
               len++;
return true;


}



}

int main()
{
DList<int> D1;
int a=2,b=3;
cout<<D1.Insert(0,a); //插入不成功!!! 
cout<<D1.Insert(1,a);
//cout<<D1.GetElem(0);
return 0;

}

为什么插入总是不成功?从一个空链表如何变成一串。。。还有,怎么样就是有头结点,怎样就是没有头结点?谢谢大家了,请大家多多指教?
[解决办法]
目测lz的DList是不带头指针的,下面的代码可能有问题:


tmp=Locate(pos);
tmp1=tmp->next; 

第一次插入操作之前链表为空,Locate(pos)返回是NULL,tmp->next = NULL->next,段异常了吧就
所以插入操作之前应该先检查,当前链表的长度,如果长度为0,则表示插入第1个节点,应该成为头节点:

if(Length() == 0){
    head = new Node<Type>(e);
    head->pre = head->next = head;
}
else{
   //insertion
}

热点排行