在这种情况下,我需要实现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++;
}
上午我做正确?如果不是,为什么?如果是的话,有没有更好的方法来做到这一点?
这功课吗? –
@JohnDibling这取决于你。 – FlowerFire
不可以。对于其中一种情况,您在初始插入时泄漏了内存。您也没有将'dummyNode'初始化为'List'构造的nullptr。在取消引用之前,您从不检查'dummyNode'是否为nullptr。这甚至没有试图运行这个。 (a)不,(b)因为你不知道如何编写一个链表,(c)最后一个问题在前两个问题之后是没有意义的。并且否认第一个问你任何关于这个问题的人是不是开始工作的方式。 – WhozCraig