Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct Node{
- int data;
- Node* next{};
- Node* prev{};
- };
- class DLL{
- private:
- Node* root{};
- Node* tail;
- void clear_helper(Node* &curr);
- public:
- void clear();
- void add(int zahl);
- void push_front(int zahl);
- void push_back(int zahl);
- int pop_front();
- int pop_back();
- DLL(){};
- ~DLL(){ clear(); };
- };
- void DLL::clear_helper(Node* &curr) { //CLEAR_HELPER
- if (curr -> next != nullptr) {
- clear_helper(curr -> next);
- } else {
- delete curr;
- curr = nullptr;
- }
- }
- void DLL::clear() { //CLEAR FUNKTION
- if (root != nullptr) {
- clear_helper(root);
- delete tail;
- tail = nullptr;
- }
- }
- void DLL::push_front(int zahl){
- if (root == nullptr) {
- root = new Node;
- root -> data = zahl;
- tail = root;
- } else {
- Node* tmp = new Node;
- tmp -> data = zahl;
- tmp -> next = root;
- root -> prev = tmp;
- root = tmp;
- }
- }
- void DLL::push_back(int zahl) {
- if (root == nullptr) {
- root = new Node;
- root -> data = zahl;
- tail = root;
- } else {
- Node *tmp = new Node;
- tmp -> data = zahl;
- tmp -> prev = tail;
- tail -> next = tmp;
- tail = tmp;
- }
- }
- int DLL::pop_front() {
- if (root == nullptr) {
- throw logic_error("Liste leer");
- } else {
- Node* tmp = root;
- int ret = tmp -> data;
- root = root -> next;
- if (root == nullptr) { //if last element was popped
- tail = nullptr;
- } else {
- root -> prev = nullptr; //prev of first element has to be NULL
- }
- delete tmp;
- return ret;
- }
- }
- int DLL::pop_back() {
- if (root == nullptr) {
- throw logic_error("List already empty!");
- } else {
- int ret = tail -> data;
- if (root != nullptr && tail == root && root -> next == nullptr) { //only one element in list
- delete tail;
- root = nullptr;
- tail = nullptr;
- } else {
- Node* tmp = tail;
- tail -> prev -> next = nullptr;
- tail = tail -> prev;
- delete tmp;
- }
- return ret;
- }
- }
- void DLL::add(int zahl) {
- if(root==nullptr){
- root = new Node;
- root->data = zahl;
- tail = root;
- }
- else{
- Node *curr = root;
- while (curr != nullptr && curr -> data > zahl) {
- curr = curr -> next;
- }
- if (curr -> prev == nullptr) {
- Node *tmp = new Node;
- tmp -> data = zahl;
- root = tmp;
- tmp -> next = curr;
- curr -> prev = tmp;
- } else if (curr == nullptr){
- Node *tmp = new Node;
- tmp -> data = zahl;
- tail -> next = tmp;
- tmp -> prev = tail;
- } else {
- Node *tmp = new Node;
- tmp -> data = zahl;
- tmp -> prev = curr -> prev;
- tmp -> next = curr;
- curr -> prev -> next = tmp;
- curr -> next -> prev = tmp;
- }
- }
- }
- int main(){
- DLL y;
- y.push_back(2);
- y.push_back(4);
- y.pop_back();
- y.pop_front();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement