I am trying to implement the pop function of a linked list in C++. My Node and Linked List classes look like this:
//Node class
template <class T>
class Node{
public:
T data;
Node<T> *next;
Node(T data, Node<T> *next);
~Node();
};
template <class T>
Node<T>::Node(T data, Node<T> *next){
this->next = next;
this->data = data;
}
template <class T>
Node<T>::~Node(){
delete this;
}
//LinkedList class
template <class T>
class LinkedList{
public:
//fields
Node<T> *head;
int size;
//methods
LinkedList();
void push(T data);
T pop();
void printList();
};
template <class T>
LinkedList<T>::LinkedList(){
this->head = NULL;
this->size = 0;
}
template <class T>
void LinkedList<T>::printList(){
int i = 1;
while(head){
std::cout<<i<<": "<<head->data<<std::endl;
head = head->next;
i++;
}
}
int main(){
LinkedList<int> list;
for (int i = 1; i < 6; ++i)
list.push(i);
list.printList();
for (int j = 0; j < 3; ++j){
int output=list.pop();
printf("popped: %d\n", output);
}
list.printList();
return 0;
}
Below is my pop function. The problem is that this->head is returning NULL. hence I cannot change its value or access its data field. I used print statements to find out that this->head is returning NULL. How can I resolve this issue?
template <class T>
T LinkedList<T>::pop(){
Node<T> *h = this->head;
//if list is empty
if (this->size==0){
return 0;
}
//if list has only one node
if (this->size==1){
T ret = h->data;
this->head = NULL;
this->size --;
return ret;
}
//if list has multiple nodes
else{
T ret = this->head->data;
this -> head = h->next;
return ret;
}
h.~Node<T>();
}
Below if my push function. I have tested this function and it works fine, but please let me know if it is not handling node pointers properly.
template <class T>
void LinkedList<T>::push(T data){
Node<T> *n = new Node<T>(data, this->head);
this->head = n;
this->size++;
}