在这种情况下,我需要实现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++;
}
我做得对吗?如果不是,为什么?如果是,有没有更好的方法来做到这一点?