doubly linked list, most functions (updated)
chamanEiqbal
c_cpp
24 days ago
2.9 kB
3
Indexable
Never
#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 insertAtPosition(Node* head, int data, int pos) { Node* temp = new Node(); temp->data = data; Node* current = head->next; int i = 1; if(head->next == NULL) { insertAtBeginning(head, data); } else { while(i < pos && current->next != NULL) { current = current->next; i++; } if(current->next == NULL) { insertAtEnd(tail, data); } else { Node* next = current->next; temp->next = next; temp->prev = current; next->prev = temp; } } } void deleteAtBeginning(Node* head) { if(head->next == NULL) {cout << "cannot delete." << endl; return;} Node* first = head->next; Node* second = first->next; head->next = second; second->prev = NULL; free(first); } void deleteAtEnd(Node* tail) { if(tail->prev == NULL) {cout << "cannot delete ." << endl; return;} Node* last = tail->prev; Node* secondlast = last->prev; tail->prev = secondlast; secondlast->next = NULL; free(last); } void deleteAtPosition(Node* head, int pos) { if(head->next == NULL) {cout << "cannot delete." << endl; return;} else { Node* current = head->next; Node* temp = new Node(); Node* next = new Node(); int i = 1; while(i < pos && current->next != NULL) { current = current->next; i++; } if(current->next == NULL) { deleteAtEnd(tail); } else { temp = current->next; next = temp->next; current->next = temp->next; next->prev = temp->prev; free(temp); } } } 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); insertAtPosition(head, 7,1); insertAtEnd(tail, 2); insertAtEnd(tail, 20); deleteAtPosition(head, 1); displayBack(tail); return 0; }