Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.cpp
- // XORLinkedList
- //
- // Created by Brandon T on 2016-11-08.
- // Copyright © 2016 XIO. All rights reserved.
- //
- #include <iostream>
- template<typename T>
- struct Node
- {
- T value;
- Node<T>* npx;
- inline Node<T>* operator xor (Node<T>& other)
- {
- return reinterpret_cast<Node<T>*>(reinterpret_cast<uintptr_t>(this) xor reinterpret_cast<uintptr_t>(&other));
- }
- };
- template<typename T>
- class LinkedList
- {
- private:
- Node<T>* head;
- Node<T>* tail;
- public:
- LinkedList();
- ~LinkedList();
- Node<T>* append(T value);
- void print();
- };
- template<typename T>
- LinkedList<T>::LinkedList() : head(nullptr), tail(nullptr) {}
- template<typename T>
- LinkedList<T>::~LinkedList()
- {
- Node<T>* itr = this->head;
- Node<T>* prev = nullptr;
- Node<T>* next = nullptr;
- while (itr)
- {
- next = *prev xor *itr->npx;
- prev = itr;
- itr = next;
- delete prev;
- }
- }
- template<typename T>
- Node<T>* LinkedList<T>::append(T value)
- {
- if (!this->head)
- {
- this->head = new Node<T> {.value = value, .npx = nullptr};
- this->tail = nullptr;
- return this->head;
- }
- else if (!this->tail)
- {
- this->tail = new Node<T> {.value = value, .npx = this->head};
- this->head->npx = this->tail;
- return this->tail;
- }
- else
- {
- Node<T>* node = new Node<T> {.value = value, .npx = this->tail};
- this->tail->npx = *this->tail->npx xor *node;
- this->tail = node;
- return node;
- }
- }
- template<typename T>
- void LinkedList<T>::print()
- {
- Node<T>* itr = this->head;
- Node<T>* prev = nullptr;
- Node<T>* next = nullptr;
- while (itr)
- {
- next = *prev xor *itr->npx;
- prev = itr;
- itr = next;
- printf("%d\n", prev->value);
- }
- }
- int main(int argc, const char * argv[]) {
- LinkedList<int> *list = new LinkedList<int>();
- for (int i = 0; i < 10; ++i)
- {
- list->append(i);
- }
- list->print();
- delete list;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement