Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- template <typename T>
- class List {
- struct Node {
- T data;
- Node* next;
- };
- Node* root;
- int sz;
- public:
- List();
- T at(int);
- void set(int, T);
- void insert(int, T);
- void erase(int);
- int size();
- bool isEmpty();
- void print();
- };
- template <typename T>
- List<T>::List() {
- root = NULL;
- sz = 0;
- }
- template <typename T>
- T List<T>::at(int x) {
- if (x > size()) {
- exit(2);
- }
- Node* node = root;
- for (int i = 0; i < x; i++) {
- node = node->next;
- }
- cout << node->data << endl;
- }
- template <typename T>
- void List<T>::set(int x, T value) {
- if (x > size()) {
- exit(2);
- }
- Node* node = root;
- for (int i = 0; i < x; i++) {
- node = node->next;
- }
- node->data = value;
- }
- template <typename T>
- int List<T>::size() {
- return sz;
- }
- template <typename T>
- bool List<T>::isEmpty() {
- return size() > 0;
- }
- template <typename T>
- void List<T>::insert(int x, T value) {
- if (root == NULL) {
- root = new Node;
- root->data = value;
- root->next = NULL;
- sz++;
- }
- else{
- Node* tmp = new Node;
- Node* current = new Node;
- Node* previous = new Node;
- current = root;
- if (x > size()) {
- printf("%d is out of bounds of the size %d", x, size());
- exit(2);
- }
- for (int i = 0; i < x; i++) {
- previous = current;
- current = current->next;
- }
- tmp->data = value;
- previous->next = tmp;
- tmp->next = current;
- sz++;
- }
- }
- template <typename T>
- void List<T>::erase(int x) {
- if (x > size()) {
- exit(2);
- }
- Node* current = new Node;
- Node* previous = new Node;
- current = root;
- for (int i = 0; i < x; i++) {
- previous = current;
- current = current->next;
- }
- previous->next = current->next;
- }
- template <typename T>
- void List<T>::print() {
- Node* node = root;
- int i = 0;
- while (node != NULL) {
- cout << node->data << " ";
- node = node->next;
- i++;
- }
- }
- int main()
- {
- List<int> list;
- for (int i = 0; i <= 3; i++) {
- list.insert(i, i);
- }
- list.at(2);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement