2013-11-04 111 views
-2

在这种情况下,我需要实现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++; 
} 

上午我做正确?如果不是,为什么?如果是的话,有没有更好的方法来做到这一点?

+0

这功课吗? –

+0

@JohnDibling这取决于你。 – FlowerFire

+0

不可以。对于其中一种情况,您在初始插入时泄漏了内存。您也没有将'dummyNode'初始化为'List'构造的nullptr。在取消引用之前,您从不检查'dummyNode'是否为nullptr。这甚至没有试图运行这个。 (a)不,(b)因为你不知道如何编写一个链表,(c)最后一个问题在前两个问题之后是没有意义的。并且否认第一个问你任何关于这个问题的人是不是开始工作的方式。 – WhozCraig

回答

1

我不会涉及太多的细节,因为这似乎是一项家庭作业,但简短的答案是,不。

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

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

1

首先名称dummyNode表示列表的开始看起来很奇怪。将它替换为头部会好得多。你也需要一个指向列表尾部的变量。

至于你的函数,那么很简单

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

而且这将是不坏,如果等级节点曾与参数接受数据和指针的构造函数。类列表还必须具有明确定义的默认构造函数,或者其数据成员在定义时必须初始化。

+0

感谢您的建议。所以你在说什么好像我错过了一个变量指向列表的尾部正确? – FlowerFire

+0

是的,你是对的。否则,很难将元素添加到列表的尾部。所以我会在类List Node * head,* tail中定义; –

+0

是的,这就是我倾向于做的。我只想找到一个棘手的方法来解决这个问题。顺便说一下,你可以在我的代码基础上编辑吗?谢谢。 – FlowerFire

相关问题