Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template<class T>
- class LinkedList {
- public:
- LinkedList();
- LinkedList(T);
- ~LinkedList();
- void add(T);
- T pop();
- private:
- struct Node {
- T data;
- struct Node* next;
- };
- struct Node* head;
- };
- template <class T>
- LinkedList<T>::LinkedList(){
- head = nullptr;
- }
- template <class T>
- LinkedList<T>::LinkedList(T data) {
- head = new struct Node;
- head->data = data;
- head->next = nullptr;
- }
- template <class T>
- LinkedList<T>::~LinkedList() {
- while (head != nullptr) {
- pop();
- }
- }
- template <class T>
- void LinkedList<T>::add(T data) {
- struct Node *newnode = new struct Node;
- newnode->data = data;
- newnode->next = head;
- head = newnode;
- }
- template <class T>
- T LinkedList<T>::pop() {
- T data = head->data;
- struct Node* popper = head;
- head = head->next;
- delete popper;
- return data;
- }
- int main() {
- LinkedList<int> myLinkedList(10);
- myLinkedList.add(20);
- myLinkedList.add(30);
- // Prints 30
- std::cout << myLinkedList.pop() << std::endl;
- // Prints 20
- std::cout << myLinkedList.pop() << std::endl;
- // Prints 10
- std::cout << myLinkedList.pop() << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement