Advertisement
fimas

Untitled

Oct 14th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. template<class T>
  4. class LinkedList {
  5. public:
  6.     LinkedList();
  7.     LinkedList(T);
  8.     ~LinkedList();
  9.  
  10.     void add(T);
  11.     T pop();
  12. private:
  13.     struct Node {
  14.         T data;
  15.         struct Node* next;
  16.     };
  17.  
  18.     struct Node* head;
  19. };
  20.  
  21. template <class T>
  22. LinkedList<T>::LinkedList(){
  23.     head = nullptr;
  24. }
  25.  
  26. template <class T>
  27. LinkedList<T>::LinkedList(T data) {
  28.     head = new struct Node;
  29.     head->data = data;
  30.     head->next = nullptr;
  31. }
  32.  
  33. template <class T>
  34. LinkedList<T>::~LinkedList() {
  35.     while (head != nullptr) {
  36.         pop();
  37.     }
  38. }
  39.  
  40. template <class T>
  41. void LinkedList<T>::add(T data) {
  42.     struct Node *newnode = new struct Node;
  43.     newnode->data = data;
  44.     newnode->next = head;
  45.  
  46.     head = newnode;
  47. }
  48.  
  49. template <class T>
  50. T LinkedList<T>::pop() {
  51.     T data = head->data;
  52.  
  53.     struct Node* popper = head;
  54.     head = head->next;
  55.  
  56.     delete popper;
  57.  
  58.     return data;
  59. }
  60.  
  61. int main() {
  62.     LinkedList<int> myLinkedList(10);
  63.     myLinkedList.add(20);
  64.     myLinkedList.add(30);
  65.  
  66.     // Prints 30
  67.     std::cout << myLinkedList.pop() << std::endl;
  68.  
  69.     // Prints 20
  70.     std::cout << myLinkedList.pop() << std::endl;
  71.  
  72.     // Prints 10
  73.     std::cout << myLinkedList.pop() << std::endl;
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement