用双向链表实现pop功能

时间:2014-05-14 04:29:55

标签: c++ linked-list stack

void Stack::pop()
{
    Node* temp;
    if(top == NULL)
        return;
    temp = top;
    top = top->prev;
    top = top->next;
    delete temp;
}

所以我在双链表中实现pop函数时遇到了麻烦。每当我构建我的编译器崩溃。上面的代码是我正在努力的。我真的不确定如何实际取消我的顶级节点与列表之间的链接。如果你们可以在一个双重链表中解释pop功能,那就太好了。

void Stack::ToString()
{
    //needs to be implemented
    Node* cursor = top; //create a temporary pointer for top
    while(cursor->next != NULL) //When debugging this is where it crashes.
        cursor = cursor->next;
    while(cursor != NULL)
    {
        cout << cursor->content << endl;
        cursor = cursor->prev;
    }
}

1 个答案:

答案 0 :(得分:0)

该功能的逻辑存在缺陷。

让&#39;假设你在链表中有两个节点:

  top   -> +--+
           |  |
           +--+
    (next)  ^ | (prev)
            | v
  n2    -> +--+
           |  |
           +--+

然后,top->prev = n2n2->next = top

执行时:

top = top->prev;  // Now top is n2
top = top->next;  // Now top is what it used to be start with.

您没有在列表中执行任何操作,无法从列表顶部弹出top

此问题的解决方法取决于列表是否为循环。

如果列表不是循环的,您可以这样做:

Node* prev = top->prev;
Node* next = top->next;
if ( prev != NULL )
{
   prev->next = next;
}
if ( next != NULL )
{
   next->prev = prev;
}
top->next = NULL;
top->prev = NULL;

如果列表是循环的,逻辑需要更复杂一点。