我坐在图书馆里,我从头顶想出了两个功能。 removefrombottom函数和removefromtop函数,用于删除链表的底部和顶部节点。我想知道这段代码是否有用或者我的逻辑是否错误。任何建议,如果我错了将不胜感激。这是我想出的
void removefrombottom()
{
StringListNode *curr = pBottom;
pBottom = pBottom->pPrev;
delete curr;
}
void removefromtop()
{
StringListNode *curr = pTop;
pTop = pTop->pNext;
delete curr;
}
这些会不会删除链表的头尾?
答案 0 :(得分:2)
我认为在删除任何元素之前必须检查列表是否为空。当列表只有一个元素时,还要实现pTop和pBottom指针。
void removefrombottom()
{
if(pBottom != NULL){ //OR if(size > 0){
StringListNode *curr = pBottom;
pBottom = pBottom->pPrev;
if(curr == pTop) pTop = NULL;
delete curr;
//--size;
}
}
void removefromtop()
{
if(pTop != NULL){ //OR if(size > 0){
StringListNode *curr = pTop;
pTop = pTop->pNext;
if(curr == pBottom) pBottom = NULL;
delete curr;
//--size;
}
}