doubly linked list

 avatar
chamanEiqbal
c_cpp
2 years ago
1.5 kB
4
Indexable
#include <iostream>
using namespace std;

class Node {
    public:
    int data;
    Node* prev;
    Node* next;
};

Node* head = new Node();
Node* tail = new Node();


void insertAtBeginning(Node* head, int data) {
        Node* temp = new Node; 
        temp->prev = NULL;
        head->next = temp;
        temp->data = data;
        temp->next = NULL;
        
        tail->prev = temp;
}

void insertAtEnd(Node* tail, int data) {
    Node* temp = new Node();
    temp->data = data;
    Node* last = tail->prev;
    
    temp->prev = last;
    last->next = temp;
    
    tail->prev = temp;
    temp->next = NULL;
    
}

void deleteAtBeginning(Node* head) {
    Node* first = head->next;
    Node* second = first->next;
    
    head->next = second;
    second->prev = NULL;
    
    free(first);
}

void deleteAtEnd(Node* tail) {
    Node* last = tail->prev;
    Node* secondlast = last->prev;
    
    tail->prev = secondlast;
    secondlast->next = NULL;
    
    free(last);
}

void displayBack(Node* tail) {
    Node* current = tail->prev;
    
    while(current != NULL) {
        cout << current->data << endl;
        current = current->prev;
    }
}

void displayForward(Node* head) {
    Node* current = head->next;
    while(current != NULL) {
        cout << current->data << endl;
        current = current->next;
    }
}

int main() {
    insertAtBeginning(head, 1);
    insertAtEnd(tail, 3);
    insertAtEnd(tail, 5);
    deleteAtBeginning(head);
    deleteAtEnd(tail);
    displayBack(tail);
    
    return 0;
}
Editor is loading...