I am trying to implement a linkedlist in C++. I would love to get feedback on how i can improve my code. Here is what I have so far:
#include <cstdlib> #include <iostream> #include <cstdio> //Node class template <class T> class Node{ public: T data; Node<T> *next; }; //LinkedList class template <class T> class LinkedList{ public: //fields Node<T> *head; int size; //methods LinkedList(); void push(T data); T pop(); int getSize(); void printList(); }; template <class T> LinkedList<T>::LinkedList(){ this->head = NULL; this->size = 0; } template <class T> void LinkedList<T>::push(T data){ Node<T> *n; n -> data = data; n->next = this->head; this->head = n; this->size++; } template <class T> T LinkedList<T>::pop(){ Node<T> *h = this->head; //if list is empty if (h==NULL){ return 0; } //if list has only one node if (h->next == NULL){ T ret = h->data; this->head = NULL; this->size --; free(h); return ret; } //if list has multiple nodes else{ T ret = h->data; this -> head = h->next; free(h); return ret; } return 0; } //returns the size of the list. template <class T> int LinkedList<T>::getSize(){ return this->size; } template <class T> void LinkedList<T>::printList(){ Node<T>* h = this->head; int i = 1; while(head){ printf("%d: %d", i,head->data); head = head->next; i++; } } int main(){ LinkedList<int> list; for (int i = 0; i < 5; ++i) { list.push(i); } list.printList(); return 0; }