void add_first(int e) {
Node* newest = new Node(e, first);
first = newest;
n++;
}
On this code i declared a node pointer "newest".
list->add_first(4);
Let's say i call that function for the second time.
list->add_first(8)
Is it still that same *newest from the first time i called the function pointing at a new node OR did the previous *newest die after the function and on the second function call a new *newest was generated?
//Full code in case you need extra information
template <typename T>
class List {
struct Node {
T elem;
Node* next;
Node(T elem = 0, Node* next = nullptr) : elem(elem), next(next) {}
};
Node* first;
size_t n;
public:
List () : n(0), first(nullptr) {}
~List () {
while (first != nullptr) {
Node* aux = first;
first = first->next;
delete aux;
}
}
bool addFirst(T e) {
Node* newest = new Node(e, first);
first = newest;
n++;
return true;
}
bool add(T e, size_t p) {
if (p > n) return false;
if (p == 0) return addFirst(e);
Node* newest = new Node(e);
Node* aux = first;
size_t i = 1;
while (i++ < p) {
aux = aux->next;
}
newest->next = aux->next;
aux->next = newest;
n++;
return true;
}
bool addLast(T e) {
return add(e, n);
}
};