替换链表头部的问题

时间:2012-12-03 03:27:56

标签: c++ linked-list

编写一个函数在链表上进行头部插入。这是一半的工作,因为它将对象插入头部并重新附加列表,但我在某种程度上丢失了列表中的原始头节点。

如果列表是[绿色,红色,蓝色]并且我尝试插入黄色,它将起作用,但新列表将是[黄色,红色,蓝色]。

节点类是:

template<class T>
class Node
{
public:
    Node(T theData, Node<T>* theLink) : data(theData), link(theLink){}
    Node<T>* getLink( ) const { return link; }

    const T& getData( ) const { return data; }

    void setData(const T& theData) { data = theData; }
    void setLink(Node<T>* pointer) { link = pointer; }

private:
    T data;
    Node<T> *link;
};

列表存储在队列中,因此头部插入是该类的方法。队列前后有私有变量,指向列表的相应位置。

template<class T>
void Queue<T>::headInsert(T& theData)
{
   Node<T> *temp;
   temp = front->getLink();
   front->setLink(new Node<T>(theData, temp->getLink() ));
   front = front->getLink();
}

1 个答案:

答案 0 :(得分:1)

您的问题出在setLink来电:

template<class T>
void Queue<T>::headInsert(T& theData)
{
   Node<T> *temp;
   temp = front->getLink();
   front->setLink(new Node<T>(theData, temp->getLink() )); // Right here
   front = front->getLink();
}

你实际上有很多问题。首先,我们假设我们有以下测试列表:

front = Red -> Green -> Blue -> NULL

调用temp = front->getLink()产生以下输出:

temp = Green -> Blue -> NULL

new Node<T>(theData, temp->getLink())调用theData = Yellow,然后产生:

new Node<T>(theData, temp->getLink()) = Yellow -> Blue -> NULL

调用front->setLink(new(...)然后会给您:

front = Red -> Yellow -> Blue -> NULL

最后,front = front->getLink()

front = Yellow -> Blue -> NULL

这不是你想要的。您只需要取yellow并将其弹出列表的前面:

template<class T>
void Queue<T>::headInsert(T& theData)
{
   front = new Node<T>(theData, front);
}

无需修改内部指针。只需指向前面是包含数据的新节点,它的下一个指针指向旧数据。