-3

在这种情况下,我需要实现addFront()在链表前不断添加整数的方法。

    class Node{
    public:
    int data;
    Node* next;
    Node* prev;
    }
    class List {

    void addFront(int item);

    protected: 
    Node* dummyNode;
    int numItems; //number of item is the linkedlist
};   

以下是我倾向于实施的addFront()

  void addFront(int data){
    Node* head = new Node();


    if(numItems == 0) //if no item in the list.
    {
      //Set the head node to be dummyNode
      head = dummyNode;

      //Because the next node the head is pointing to is NULL.
      head -> next = NULL;
    }

    //Create a new node.
    Node* newNode = new Node();

    //Set value
    newNode->data = data;

    //Let the previous pointer of dummyNode points to newNode.
    head->prev = newNode;

    //Re-set head to be newNode.
    head = newNode;

    numItems++;
}

我做得对吗?如果不是,为什么?如果是,有没有更好的方法来做到这一点?

4

2 回答 2

1

我不会详细介绍,因为这似乎是一项家庭作业,但简短的回答是,不。

Node* head = new Node();
if(numItems == 0) //if no item in the list.
{
    //Set the head node to be dummyNode
    head = dummyNode;
    //...
}

您在上面的代码中存在内存泄漏。

于 2013-11-04T16:03:51.043 回答
1

首先,表示列表开头的名称 dummyNode 看起来很奇怪。用它代替头部会好得多。您还需要一个指向列表尾部的变量。

至于你的功能那么它很简单

void addFront( int data )
{
    Node *head = new Node();
    head->data = data;
    head->next = dummyNode;
    dummyNode->prev = head;
    dummyNode = head;
    numItems++;
} 

如果类 Node 有一个带有参数的构造函数来接受数据和指针,那也不错。类列表还必须有一个明确定义的默认构造函数,或者它的数据成员必须在定义时进行初始化。

于 2013-11-04T16:14:30.443 回答